<template>
    <div class="index" :class="{ 'fullscreen-mode': isFullscreen }">
        <div class="left-sidebar" :class="{ 'hidden': isFullscreen }">
            <!-- 左侧菜单内容 -->
        </div>
        <div class="dashboard">
            <HeaderSection
                :data-status="dataStatus"
                :is-fullscreen="isFullscreen"
                @toggle-fullscreen="toggleFullscreen"
            />

            <!-- 主要内容区 -->
            <div class="content">
                <LeftModule
                    :device-status="deviceStatus"
                    :total-devices="totalDevices"
                    :monitor-logs="monitorLogs"
                    :lathe-names-to-animate="latheNamesToAnimate"
                    :unique-lathe-names="uniqueLatheNames"
                    :get-lathe-name-status="getLatheNameStatus"
                    :lathe-name-summaries="latheNameSummaries"
                    :current-device="currentDevice"
                    :show-detection-card="true"
                    @update-circle-progress="updateCircleProgress"
                    @inquiry-from-log="inquiryFromLog"
                    @select-device="selectLatheNameDevice"
                    @inquiry-from-device="inquiryFromDevice"
                />

                <CenterModule
                    :workshops="workshops"
                    :current-workshop="currentWorkshop"
                    :unique-lathe-names="uniqueLatheNames"
                    :current-device="currentDevice"
                    :auto-hover-device-name="autoHoverDeviceName"
                    :get-lathe-name-status="getLatheNameStatus"
                    :get-lathe-name-icon="getLatheNameIcon"
                    :device-has-real-lathe-name="deviceHasRealLatheName"
                    @switch-workshop="switchWorkshop"
                    @select-lathe-name-device="selectLatheNameDevice"
                    @device-item-mouse-enter="handleDeviceItemMouseEnter"
                    @device-item-mouse-leave="handleDeviceItemMouseLeave"
                    @inquiry-from-log="inquiryFromLog"
                />

                <RightTopModule :health-score="healthScore" />

                <RightBottomModule
                    :current-device="currentDevice"
                    :device-positions="devicePositions"
                    :current-position="currentPosition"
                    :acceleration-type="accelerationType"
                    :device-acceleration-data="deviceAccelerationData"
                    :get-lathe-name-status="getLatheNameStatus"
                    @switch-position="switchPosition"
                    @switch-acceleration-type="switchAccelerationType"
                    @go-to-inquiry="goToInquiry"
                />
            </div>
            <DataStatus @toggle-fullscreen="toggleFullscreen" />
        </div>
    </div>
</template>

<script>
import * as echarts from 'echarts'
import { getStatus, getAccelerationData, getDetectInfo } from '../../../api/real/detect'
import { getWaveformDataByrangeTime } from '../../../api/real/waveform'

import 'echarts-liquidfill'

// 导入WebSocket和新的数据管理器
import DeviceWebSocketService from '../../../utils/websocket'
import ChartDataManager from '../../../utils/chartDataManager'

// 导入组件
import HeaderSection from './components/HeaderSection.vue'
import LeftModule from './components/LeftModule.vue'
import CenterModule from './components/CenterModule.vue'
import RightTopModule from './components/RightTopModule.vue'
import RightBottomModule from './components/RightBottomModule.vue'
import DataStatus from './components/DataStatus.vue'


export default {
    name: "Index",
    components: {
        HeaderSection,
        LeftModule,
        CenterModule,
        RightTopModule,
        RightBottomModule,
        DataStatus
    },
    data() {
        return {

            deviceStatusMap: {
                '正常': 'normal',
                '故障': 'warning',
                '待机': 'waiting',
                '离线': 'offline'
            },
            deviceStatusData: [],
            deviceStatus: {
                normalCount: 0,
                normalRate: 0,
                warningCount: 0,
                warningRate: 0,
                waitingCount: 0,
                waitingRate: 0,
                offlineCount: 0,
                offlineRate: 0
            },
            totalDevices: 35,
            DevicesId: [30096429, 30096457, 30096464,30096424, 30096546, 20031108, 30096407, 30096408, 30096409, 30096410, 30096411, 30096412, 30096413, 30096414, 30096415, 30096416, 30096417, 30096418, 30096419, 30096420, 30096421, 30096422, 30096423, 30096437, 30096438, 30096439, 30096440, 30096441, 30096442, 30096443, 30096444, 30096445, 30096446, 30096447,30096448,30096570],
            runningRates: [85, 82, 88, 84, 86, 83, 87],  // 运行率数据
            monitorLogs: [],
            loading: false,
            timer: null,
            accelerationData: {
                rms: {
                    x: Array(15).fill(0),  // 修改为15个点，对应75分钟
                    y: Array(15).fill(0),
                    z: Array(15).fill(0)
                },
                peak: {
                    x: Array(15).fill(0),
                    y: Array(15).fill(0),
                    z: Array(15).fill(0)
                }
            },
            updateInterval: 2000,
            dataUpdateTimer: null,
            dataStatus: {
                updating: false,
                lastUpdate: '',
                errorCount: 0
            },
            // 轮询控制相关
            enablePolling: false, // 默认禁用轮询
            forceDisablePolling: true, // 强制禁用轮询
            pollingDisabledByUser: true, // 用户主动禁用轮询
            previousData: null, // 用于存储上一次的数据，实现平滑过渡
            currentDevice: {
                id: 30096546,
                name: '设备 01',
                latheName: '设备', // 添加latheName属性
                peakHistory: [] // 存储历史 peak 值的数组
            },
            maxPeakPoints: 100, // 最多保存100个数据点
            timeData: Array(30).fill('').map((_, index) => {  // 30个点，每点间隔1分钟
                const time = new Date(Date.now() - (29 - index) * 60000); // 每点间隔1分钟(60,000毫秒)
                return time.toLocaleTimeString('zh-CN', {
                    hour: '2-digit',
                    minute: '2-digit',
                });
            }),
            healthScore: {
                score: 100,
                details: [],
                status: 'normal'
            },
            timePoints: ['0', '2', '4', '6', '10', '12', '14', '16', '18', '20', '22', '24'],
            isFullscreen: false,
            fullscreenHandler: null,
            accelerationType: 'rms', // 新增：加速度类型
            accelerationHistory: [], // 存储加速度历史数据
            maxHistoryPoints: 30,   // 显示30个数据点
            accelerationTimer: null, // 添加定时器引用
            workshops: [
                { id: 1, name: '一期车间' },
                { id: 2, name: '二期车间' },
                { id: 3, name: '三期车间' }
            ],
            currentWorkshop: 1, // 默认选中车间一
            deviceAccelerationData: {}, // 存储每个设备的加速度数据
            devicePositions: [], // 存储设备安装位置列表
            currentPosition: '', // 当前选中的安装位置
            latheNameList: [], // 存储所有设备的latheName列表
            latheNameToDeviceMap: {}, // latheName到deviceId的映射
            uniqueLatheNames: [], // 唯一的latheName列表，用于网格显示
            monitorLogTimer: null, // 新增监测记录轮播定时器
            autoHoverDeviceName: null, // 当前自动悬浮的设备名称
            autoHoverTimer: null, // 自动悬浮定时器ID
            autoHoverInterval: 5000, // 自动悬浮间隔，例如5秒
            currentAutoHoverIndex: -1, // 当前自动悬浮的设备索引
            tooltipPositionAdjusted: false, // 标记提示框位置是否已调整
            lastHoveredWarningDevice: null, // 记录最后一个悬浮显示的故障设备
            previousLatheNameStatuses: {}, // 新增：存储设备之前的状态
            latheNamesToAnimate: new Set(), // 新增：需要播放状态变化动画的设备名集合
            newlyFaultyLatheNames: new Set(), // 新增：用于跟踪最新故障设备
            latheNameSummaries: {}, // 新增：用于存储每个latheName的聚合状态和最新收集时间
            monitorLogDisplayOffset: 0, // 新增：用于监测记录轮播的偏移量
            lastNotifiedFaults: new Set(), // 新增：已弹出 Toast 的故障设备

            // WebSocket和实时数据相关
            useWebSocket: true, // 启用WebSocket模式
            webSocketService: null, // WebSocket服务实例
            chartDataManager: null, // 新的图表数据管理器
            isWebSocketConnected: false, // WebSocket连接状态
            webSocketReconnectAttempts: 0, // 重连尝试次数
            maxWebSocketReconnectAttempts: 5, // 最大重连次数
        }
    },
    created() {
        // 初始化设备加速度数据存储（延迟初始化，避免大规模预分配）
        this.deviceAccelerationData = {};

        // 立即获取设备状态数据
        console.log('🚀 页面加载，开始获取设备状态...');

        // 优化：仅执行关键的数据获取，WebSocket延迟初始化
        this.getList().then(() => {
            console.log('✅ 核心数据获取完成');

            // 轻量级加速度数据预处理（仅获取映射关系，不预分配大数组）
            return this.prefetchAccelerationDataLightweight();
        }).then(() => {
            console.log('✅ 设备映射关系建立完成');

            // 设置第一台设备为当前设备
            const firstLatheName = this.uniqueLatheNames[0];
            const firstDeviceId = this.latheNameToDeviceMap[firstLatheName]?.[0] || this.DevicesId[0];

            this.currentDevice = {
                id: firstDeviceId,
                name: firstLatheName || this.getDeviceName(firstDeviceId),
                latheName: firstLatheName,
                putPlace: '', // 延迟获取，避免初始化阻塞
            };

            // 异步初始化图表和其他数据，避免阻塞主线程
            this.$nextTick(() => {
                this.initCharts();

                // 统一延迟执行所有非关键初始化，避免分散的卡顿
                setTimeout(() => {
                    this.initializeNonCriticalDataAsync();
                }, 3000); // 延迟3秒，让页面完全稳定后再执行
            });

        }).catch(error => {
            console.error('❌ 数据初始化失败:', error);
        });

        // 恢复监测记录轮播
        this.startMonitorLogCarousel();
    },

    mounted() {
        // 移除重复的 initCharts() 调用，避免重复初始化

        // 添加全屏变化监听
        const fullscreenHandler = () => {
            this.isFullscreen = document.fullscreenElement !== null;
            // 移除不必要的 $nextTick，减少异步调用
        };

        document.addEventListener('fullscreenchange', fullscreenHandler);
        document.addEventListener('webkitfullscreenchange', fullscreenHandler);
        document.addEventListener('onfullscreenchange', fullscreenHandler);
        document.addEventListener('MSFullscreenChange', fullscreenHandler);

        // 添加全屏变化监听
        document.addEventListener('fullscreenchange', this.handleFullscreenChange);

        // 注释掉加速度轮询
        // if (!this.enablePolling || this.forceDisablePolling || this.pollingDisabledByUser) {
        //     console.log('🛑 轮询已被禁用，跳过加速度轮询');
        // } else {
        //     console.log('🔄 启动加速度轮询');
        //     // 增加加速度图表数据更新频率，使波动更明显
        //     if (this.accelerationTimer) {
        //         clearInterval(this.accelerationTimer);
        //     }
        //     this.accelerationTimer = setInterval(() => {
        //         this.updateAccelerationChart();
        //     }, 5000); // 5秒钟刷新一次
        // }

        // 在开发环境下暴露调试方法到全局
        if (process.env.NODE_ENV === 'development') {
            window.testWebSocketMessage = this.testWebSocketMessage;
            window.checkDeviceData = () => {
                console.log('📊 当前设备数据:', this.deviceAccelerationData[this.currentDevice.id]);
                console.log('📊 当前设备ID:', this.currentDevice.id);
                console.log('📊 所有设备数据:', Object.keys(this.deviceAccelerationData));
            };
            window.checkDataManager = () => {
                if (this.chartDataManager) {
                    const status = this.chartDataManager.getDeviceStatus(this.currentDevice.id);
                    console.log('📊 数据管理器状态:', status);
                    const displayData = this.chartDataManager.getDisplayData(this.currentDevice.id, 'rms');
                    console.log('📊 显示数据:', displayData);
                } else {
                    console.log('❌ 数据管理器未初始化');
                }
            };
            window.testDeviceStatusCheck = (deviceId) => {
                const targetDeviceId = deviceId || this.currentDevice.id;
                const status = this.getDeviceStatus(targetDeviceId);
                console.log(`🔍 设备 ${targetDeviceId} 状态检查:`, status);
                console.log('📊 设备状态数据:', this.deviceStatusData.find(d => d.deviceId === targetDeviceId));
                return status;
            };
            window.testNewArchitecture = () => {
                console.log('🧪 测试新架构...');
                // 先加载历史数据
                this.loadHistoricalAccelerationData(this.currentDevice.id).then(() => {
                    console.log('✅ 历史数据加载完成');
                    // 然后发送几个实时数据
                    for (let i = 0; i < 5; i++) {
                        setTimeout(() => {
                            this.testWebSocketMessage();
                        }, i * 1000);
                    }
                });
            };
            window.testLargeValues = () => {
                console.log('🧪 测试大数值显示...');
                // 模拟大数值的WebSocket消息
                const mockMessage = {
                    type: "DEVICE_INFO_UPDATE",
                    data: [
                        {
                            deviceId: this.currentDevice.id,
                            collectTime: Date.now(),
                            temperature: 25.0,
                            latheName: this.currentDevice.latheName,
                            putPlace: this.currentDevice.putPlace || "SP1主轴电机驱动端",
                            xrms: 25 + Math.random() * 10, // 25-35范围
                            yrms: 30 + Math.random() * 5,  // 30-35范围
                            zrms: 20 + Math.random() * 15, // 20-35范围
                            xpeak: 50 + Math.random() * 20,
                            ypeak: 60 + Math.random() * 15,
                            zpeak: 40 + Math.random() * 25
                        }
                    ],
                    timestamp: Date.now()
                };

                if (this.webSocketService) {
                    this.webSocketService.handleMessage(mockMessage);
                } else {
                    this.handleWebSocketDeviceInfoUpdate(mockMessage.data);
                }
            };
            window.testXAxisDensity = () => {
                console.log('🧪 测试X轴密度...');
                // 连续发送多个数据点来测试X轴密度
                for (let i = 0; i < 20; i++) {
                    setTimeout(() => {
                        const mockMessage = {
                            type: "DEVICE_INFO_UPDATE",
                            data: [
                                {
                                    deviceId: this.currentDevice.id,
                                    collectTime: Date.now(),
                                    temperature: 25.0,
                                    latheName: this.currentDevice.latheName,
                                    putPlace: this.currentDevice.putPlace || "SP1主轴电机驱动端",
                                    xrms: 5 + Math.sin(i * 0.5) * 3,
                                    yrms: 6 + Math.cos(i * 0.3) * 2,
                                    zrms: 4 + Math.sin(i * 0.7) * 2.5,
                                    xpeak: 10 + Math.sin(i * 0.5) * 6,
                                    ypeak: 12 + Math.cos(i * 0.3) * 4,
                                    zpeak: 8 + Math.sin(i * 0.7) * 5
                                }
                            ],
                            timestamp: Date.now()
                        };

                        if (this.webSocketService) {
                            this.webSocketService.handleMessage(mockMessage);
                        } else {
                            this.handleWebSocketDeviceInfoUpdate(mockMessage.data);
                        }
                    }, i * 500); // 每500ms发送一个
                }
            };
            window.testStableAxis = () => {
                console.log('🧪 测试轴线稳定性...');
                // 发送变化范围较大的数据，测试Y轴是否稳定
                const ranges = [
                    { base: 5, variation: 2 },   // 小范围
                    { base: 15, variation: 5 },  // 中等范围
                    { base: 8, variation: 3 },   // 回到小范围
                    { base: 25, variation: 8 },  // 大范围
                    { base: 12, variation: 4 }   // 回到中等范围
                ];

                ranges.forEach((range, index) => {
                    setTimeout(() => {
                        const mockMessage = {
                            type: "DEVICE_INFO_UPDATE",
                            data: [
                                {
                                    deviceId: this.currentDevice.id,
                                    collectTime: Date.now(),
                                    temperature: 25.0,
                                    latheName: this.currentDevice.latheName,
                                    putPlace: this.currentDevice.putPlace || "SP1主轴电机驱动端",
                                    xrms: range.base + (Math.random() - 0.5) * range.variation,
                                    yrms: range.base + (Math.random() - 0.5) * range.variation,
                                    zrms: range.base + (Math.random() - 0.5) * range.variation,
                                    xpeak: (range.base + (Math.random() - 0.5) * range.variation) * 2,
                                    ypeak: (range.base + (Math.random() - 0.5) * range.variation) * 2,
                                    zpeak: (range.base + (Math.random() - 0.5) * range.variation) * 2
                                }
                            ],
                            timestamp: Date.now()
                        };

                        console.log(`📊 发送范围测试数据 ${index + 1}/5:`, range);
                        if (this.webSocketService) {
                            this.webSocketService.handleMessage(mockMessage);
                        } else {
                            this.handleWebSocketDeviceInfoUpdate(mockMessage.data);
                        }
                    }, index * 2000); // 每2秒发送一个
                });
            };
            window.test10MinuteRange = () => {
                console.log('🧪 测试10分钟完整时间范围显示...');
                // 先加载历史数据，然后观察是否显示完整的10分钟范围
                this.loadHistoricalAccelerationData(this.currentDevice.id).then(() => {
                    console.log('✅ 历史数据加载完成，应该显示完整的10分钟时间范围');
                    console.log('📊 检查X轴是否显示从历史数据开始到当前时间的完整范围');

                    // 发送几个实时数据点，验证时间轴是否扩展
                    setTimeout(() => {
                        for (let i = 0; i < 3; i++) {
                            setTimeout(() => {
                                this.testWebSocketMessage();
                                if (i === 2) {
                                    console.log('✅ 实时数据发送完成，X轴应该扩展到包含新的实时数据');
                                }
                            }, i * 1000);
                        }
                    }, 1000);
                });
            };
            window.testXAxisSpace = () => {
                console.log('🧪 测试X轴空间利用...');
                // 加载历史数据并发送实时数据，检查X轴是否充分利用空间
                this.loadHistoricalAccelerationData(this.currentDevice.id).then(() => {
                    console.log('✅ 历史数据加载完成');
                    console.log('📊 检查要点:');
                    console.log('  1. X轴左右边距是否最小化');
                    console.log('  2. 第一个时间标签是否显示（历史数据开始时间）');
                    console.log('  3. 最后一个时间标签是否显示（最新数据时间）');
                    console.log('  4. 时间标签是否充分利用可用空间');

                    // 发送实时数据，观察最新时间是否显示
                    setTimeout(() => {
                        this.testWebSocketMessage();
                        console.log('📊 发送实时数据，检查最新时间是否在X轴右端显示');
                    }, 2000);
                });
            };
            console.log('🧪 调试方法已暴露:');
            console.log('  - window.testWebSocketMessage() - 测试WebSocket消息处理');
            console.log('  - window.checkDeviceData() - 检查当前设备数据');
            console.log('  - window.checkDataManager() - 检查数据管理器状态');
            console.log('  - window.testNewArchitecture() - 测试新架构');
            console.log('  - window.testLargeValues() - 测试大数值显示（25-35范围）');
            console.log('  - window.testXAxisDensity() - 测试X轴密度（连续发送20个数据点）');
            console.log('  - window.testStableAxis() - 测试轴线稳定性（不同数值范围）');
            console.log('  - window.test10MinuteRange() - 测试10分钟完整时间范围显示');
            console.log('  - window.testXAxisSpace() - 测试X轴空间利用和最新时间显示');
        }
    },
    beforeDestroy() {
        this.stopDataUpdate()

        // 图表销毁由各个组件自己管理
        window.removeEventListener('resize', this.handleResize)

        // 移除监听器
        document.removeEventListener('fullscreenchange', this.fullscreenHandler);
        document.removeEventListener('webkitfullscreenchange', this.fullscreenHandler);
        document.removeEventListener('onfullscreenchange', this.fullscreenHandler);
        document.removeEventListener('MSFullscreenChange', this.fullscreenHandler);
        if (this.liquidChart) {
            this.liquidChart.dispose()
            this.liquidChart = null
        }
        if (this.accelerationTimer) {
            clearInterval(this.accelerationTimer);
            this.accelerationTimer = null;
        }
        if (this.deviceStatusChart) {
            this.deviceStatusChart.dispose();
            this.deviceStatusChart = null;
        }
        // 移除监听器
        document.removeEventListener('fullscreenchange', this.handleFullscreenChange);
        if (this.monitorLogTimer) {
            clearInterval(this.monitorLogTimer);
            this.monitorLogTimer = null;
        }
        this.stopAutoDeviceHover(); // 组件销毁前停止自动悬浮

        // 清理WebSocket和滑动窗口管理器
        this.cleanupWebSocketAndWindowManager();

        // 清理连续测试定时器
        if (this.continuousTestTimer) {
            clearInterval(this.continuousTestTimer);
            this.continuousTestTimer = null;
        }
    },
    computed: {

    },
    methods: {
        // Helper function to format date/time for API calls
        formatTimeForApi(date) {
            if (!(date instanceof Date)) {
                date = new Date(date);
            }
            if (isNaN(date.getTime())) {
                console.error("Invalid date received in formatTimeForApi:", date);
                const now = new Date();
                const year = now.getFullYear();
                const month = (now.getMonth() + 1).toString().padStart(2, '0');
                const day = now.getDate().toString().padStart(2, '0');
                const hours = now.getHours().toString().padStart(2, '0');
                const minutes = now.getMinutes().toString().padStart(2, '0');
                const seconds = now.getSeconds().toString().padStart(2, '0');
                return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
            }
            const year = date.getFullYear();
            const month = (date.getMonth() + 1).toString().padStart(2, '0');
            const day = date.getDate().toString().padStart(2, '0');
            const hours = date.getHours().toString().padStart(2, '0');
            const minutes = date.getMinutes().toString().padStart(2, '0');
            const seconds = date.getSeconds().toString().padStart(2, '0');
            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        },

        /**
         * 为非正常状态的设备初始化空数据结构
         * 避免因为没有数据而导致的UI错误
         */
        initializeEmptyDeviceData(deviceId) {
            console.log(`🔧 为设备 ${deviceId} 初始化空数据结构`);

            // 创建时间点数组（60个点，覆盖10分钟）
            const timePoints = Array(60).fill('').map((_, index) => {
                const time = new Date(Date.now() - (59 - index) * 10000); // 10秒间隔
                return time.toLocaleTimeString('zh-CN', {
                    hour: '2-digit',
                    minute: '2-digit',
                    second: '2-digit'
                });
            });

            // 确保设备数据结构存在
            if (!this.deviceAccelerationData[deviceId]) {
                this.deviceAccelerationData[deviceId] = {
                    latheName: this.currentDevice.latheName || '',
                    putPlace: this.currentDevice.putPlace || '',
                    deviceLocation: '',
                    bindLocation: '',
                    rms: {
                        x: Array(60).fill(null),
                        y: Array(60).fill(null),
                        z: Array(60).fill(null)
                    },
                    peak: {
                        x: Array(60).fill(null),
                        y: Array(60).fill(null),
                        z: Array(60).fill(null)
                    },
                    timeData: timePoints,
                    lastUpdateTime: Date.now()
                };
            }

            console.log(`✅ 设备 ${deviceId} 空数据结构初始化完成`);
        },

        /**
         * 处理设备latheName变化
         * 监听设备名称的变化，用于触发相关的更新逻辑
         */
        handleLatheNameChanges(newDeviceData, oldDeviceData) {
            console.log('🔄 处理设备latheName变化...');

            if (!Array.isArray(newDeviceData) || !Array.isArray(oldDeviceData)) {
                console.warn('⚠️ 设备数据格式不正确，跳过latheName变化处理');
                return;
            }

            // 构建新旧数据的映射，便于比较
            const oldDeviceMap = new Map();
            oldDeviceData.forEach(device => {
                if (device.deviceId) {
                    oldDeviceMap.set(device.deviceId, device.latheName || '');
                }
            });

            const changedDevices = [];

            // 检查每个设备的latheName是否发生变化
            newDeviceData.forEach(device => {
                if (device.deviceId) {
                    const oldLatheName = oldDeviceMap.get(device.deviceId);
                    const newLatheName = device.latheName || '';

                    if (oldLatheName !== newLatheName) {
                        changedDevices.push({
                            deviceId: device.deviceId,
                            oldLatheName,
                            newLatheName
                        });
                    }
                }
            });

            if (changedDevices.length > 0) {
                console.log('📊 检测到latheName变化的设备:', changedDevices);

                // 触发相关的更新逻辑
                this.onLatheNameChanged(changedDevices);
            } else {
                console.log('✅ 没有检测到latheName变化');
            }
        },

        /**
         * 当设备latheName发生变化时的处理逻辑
         */
        onLatheNameChanged(changedDevices) {
            console.log('🔄 处理latheName变化事件:', changedDevices);

            changedDevices.forEach(change => {
                const { deviceId, oldLatheName, newLatheName } = change;

                // 如果当前选中的设备发生了latheName变化，需要更新当前设备信息
                if (this.currentDevice && this.currentDevice.id === deviceId) {
                    console.log(`📱 当前设备 ${deviceId} 的latheName从 "${oldLatheName}" 变更为 "${newLatheName}"`);
                    this.currentDevice.latheName = newLatheName;
                    this.currentDevice.name = newLatheName;
                }

                // 更新设备加速度数据中的latheName
                if (this.deviceAccelerationData[deviceId]) {
                    this.deviceAccelerationData[deviceId].latheName = newLatheName;
                }
            });

            // 优化：避免强制刷新，让Vue自然响应数据变化
            // this.$nextTick(() => {
            //     this.$forceUpdate();
            // });
        },

        async loadHistoricalAccelerationData(deviceId) {
            if (!deviceId) return;

            // 检查设备状态，只有正常状态的设备才请求波形数据
            const deviceStatus = this.getDeviceStatus(deviceId);
            console.log(`📊 设备 ${deviceId} 当前状态: ${deviceStatus}`);

            if (deviceStatus !== '正常') {
                console.log(`⚠️ 设备 ${deviceId} 状态为 "${deviceStatus}"，跳过波形数据请求`);
                // 为非正常状态的设备初始化空数据结构
                this.initializeEmptyDeviceData(deviceId);
                return;
            }

            console.log(`✅ 设备 ${deviceId} 状态正常，开始请求波形数据`);

            const endTime = new Date();
            const startTime = new Date(endTime.getTime() - 10 * 60 * 1000); // Last 10 minutes

            const formattedStartTime = this.formatTimeForApi(startTime);
            const formattedEndTime = this.formatTimeForApi(endTime);

            try {
                const res = await getWaveformDataByrangeTime(deviceId, formattedStartTime, formattedEndTime);
                if (res.code === 200 && res.data && res.data.length > 0) {
                    const historicalData = res.data[0]; // Assuming the first element contains the relevant data
                    const extraData = historicalData.extraData || {};
                    const timestamps = historicalData.timestamps || [];

                    const numPoints = 60; // Desired number of points for the chart

                    // Initialize arrays for processed data
                    let newTimeData = Array(numPoints).fill(null);
                    let newRmsX = Array(numPoints).fill(null);
                    let newRmsY = Array(numPoints).fill(null);
                    let newRmsZ = Array(numPoints).fill(null);
                    let newPeakX = Array(numPoints).fill(null);
                    let newPeakY = Array(numPoints).fill(null);
                    let newPeakZ = Array(numPoints).fill(null);

                    const apiRmsX = extraData.xRmsData || [];
                    const apiRmsY = extraData.yRmsData || [];
                    const apiRmsZ = extraData.zRmsData || [];
                    const apiPeakX = extraData.xPeakData || [];
                    const apiPeakY = extraData.yPeakData || [];
                    const apiPeakZ = extraData.zPeakData || [];

                    const availablePoints = timestamps.length;
                    const startIndex = Math.max(0, availablePoints - numPoints);
                    const pointsToProcess = availablePoints - startIndex;

                    for (let i = 0; i < pointsToProcess; i++) {
                        const apiIndex = startIndex + i;
                        const chartIndex = numPoints - pointsToProcess + i;

                        if (timestamps[apiIndex]) {
                            newTimeData[chartIndex] = new Date(timestamps[apiIndex]).toLocaleTimeString('zh-CN', {
                                hour: '2-digit',
                                minute: '2-digit',
                                second: '2-digit'
                            });
                        }
                        newRmsX[chartIndex] = apiRmsX[apiIndex] !== undefined ? apiRmsX[apiIndex] : null;
                        newRmsY[chartIndex] = apiRmsY[apiIndex] !== undefined ? apiRmsY[apiIndex] : null;
                        newRmsZ[chartIndex] = apiRmsZ[apiIndex] !== undefined ? apiRmsZ[apiIndex] : null;
                        newPeakX[chartIndex] = apiPeakX[apiIndex] !== undefined ? apiPeakX[apiIndex] : null;
                        newPeakY[chartIndex] = apiPeakY[apiIndex] !== undefined ? apiPeakY[apiIndex] : null;
                        newPeakZ[chartIndex] = apiPeakZ[apiIndex] !== undefined ? apiPeakZ[apiIndex] : null;
                    }

                    // Ensure the device data structure exists
                    if (!this.deviceAccelerationData[deviceId]) {
                         // Create 10秒间隔的时间点（60个点，覆盖10分钟）
                        const initialTimePoints = Array(60).fill('').map((_, index) => {
                            const time = new Date(Date.now() - (59 - index) * 10000); // 10秒 = 10000毫秒
                            return time.toLocaleTimeString('zh-CN', {
                                hour: '2-digit',
                                minute: '2-digit',
                                second: '2-digit' // 添加秒显示
                            });
                        });
                        this.deviceAccelerationData[deviceId] = {
                            latheName: this.currentDevice.latheName || '', // Get from currentDevice or an alternative source
                            putPlace: this.currentDevice.putPlace || '',  // Get from currentDevice
                            deviceLocation: '', // These might need to be set from another source or kept empty
                            bindLocation: '',
                            rms: { x: [], y: [], z: [] },
                            peak: { x: [], y: [], z: [] },
                            timeData: initialTimePoints,
                            lastUpdateTime: 0
                        };
                    }

                    // Update the device's acceleration data store
                    this.deviceAccelerationData[deviceId].timeData = newTimeData;
                    this.deviceAccelerationData[deviceId].rms = { x: newRmsX, y: newRmsY, z: newRmsZ };
                    this.deviceAccelerationData[deviceId].peak = { x: newPeakX, y: newPeakY, z: newPeakZ };
                    this.deviceAccelerationData[deviceId].lastUpdateTime = Date.now(); // Mark as updated
                    this.deviceAccelerationData[deviceId].hasHistoricalData = true; // 标记已加载历史数据

                    console.log(`✅ 设备 ${deviceId} 历史数据加载完成，数据点数: ${pointsToProcess}`);

                    // 优化：避免强制响应式更新，减少性能开销
                    // this.$set(this.deviceAccelerationData, deviceId, { ...this.deviceAccelerationData[deviceId] });

                    // 图表刷新由组件自己处理
                } else {
                    console.warn(`No historical acceleration data found for device ${deviceId} in the last 10 minutes.`);
                    // If no historical data, initialize with nulls as before,
                    // so the live updates can still populate it.
                     if (!this.deviceAccelerationData[deviceId]) {
                        const timePoints = Array(60).fill('').map((_, index) => {
                            const time = new Date(Date.now() - (59 - index) * 10000);
                            return time.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit', second: '2-digit' });
                        });
                        this.deviceAccelerationData[deviceId] = {
                            latheName: this.currentDevice.latheName || '',
                            putPlace: this.currentDevice.putPlace || '',
                            deviceLocation: '', bindLocation: '',
                            rms: { x: Array(60).fill(null), y: Array(60).fill(null), z: Array(60).fill(null) },
                            peak: { x: Array(60).fill(null), y: Array(60).fill(null), z: Array(60).fill(null) },
                            timeData: timePoints,
                            lastUpdateTime: Date.now()
                        };
                    } else { // Ensure existing data is reset to nulls if history fetch fails
                        this.deviceAccelerationData[deviceId].timeData = this.deviceAccelerationData[deviceId].timeData.map(() => null);
                        this.deviceAccelerationData[deviceId].rms = { x: Array(60).fill(null), y: Array(60).fill(null), z: Array(60).fill(null) };
                        this.deviceAccelerationData[deviceId].peak = { x: Array(60).fill(null), y: Array(60).fill(null), z: Array(60).fill(null) };
                    }
                     // 图表刷新由组件自己处理
                }
            } catch (error) {
                console.error('Failed to load historical acceleration data:', error);
                // Initialize with nulls on error too
                if (!this.deviceAccelerationData[deviceId]) {
                    const timePoints = Array(60).fill('').map((_, index) => {
                        const time = new Date(Date.now() - (59 - index) * 10000);
                        return time.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit', second: '2-digit' });
                    });
                    this.deviceAccelerationData[deviceId] = {
                        latheName: this.currentDevice.latheName || '',
                        putPlace: this.currentDevice.putPlace || '',
                        deviceLocation: '', bindLocation: '',
                        rms: { x: Array(60).fill(null), y: Array(60).fill(null), z: Array(60).fill(null) },
                        peak: { x: Array(60).fill(null), y: Array(60).fill(null), z: Array(60).fill(null) },
                        timeData: timePoints,
                        lastUpdateTime: Date.now()
                    };
                } else {
                     this.deviceAccelerationData[deviceId].timeData = this.deviceAccelerationData[deviceId].timeData.map(() => null);
                     this.deviceAccelerationData[deviceId].rms = { x: Array(60).fill(null), y: Array(60).fill(null), z: Array(60).fill(null) };
                    this.deviceAccelerationData[deviceId].peak = { x: Array(60).fill(null), y: Array(60).fill(null), z: Array(60).fill(null) };
                }
                // 图表刷新由组件自己处理
            }
        },
        // 定时更新相关方法 - 已注释掉轮询
        startDataUpdate() {
            // 注释掉轮询逻辑
            // if (!this.enablePolling || this.forceDisablePolling || this.pollingDisabledByUser) {
            //     console.log('🛑 轮询已被禁用，跳过HTTP轮询');
            //     return;
            // }

            console.log('🛑 轮询已被注释，不启动HTTP轮询');
            // this.getList() // 立即获取一次数据
            // this.dataUpdateTimer = setInterval(() => {
            //     this.getList()
            // }, this.updateInterval)
        },

        stopDataUpdate() {
            if (this.dataUpdateTimer) {
                clearInterval(this.dataUpdateTimer)
                this.dataUpdateTimer = null
            }
        },



        // 停止所有定时器（用于调试）
        stopAllTimers() {
            console.log('🛑 停止所有定时器...');

            // 停止数据更新定时器
            this.stopDataUpdate();

            // 停止加速度定时器
            if (this.accelerationTimer) {
                clearInterval(this.accelerationTimer);
                this.accelerationTimer = null;
            }

            // 停止其他定时器
            if (this.autoHoverTimer) {
                clearInterval(this.autoHoverTimer);
                this.autoHoverTimer = null;
            }

            if (this.monitorLogTimer) {
                clearInterval(this.monitorLogTimer);
                this.monitorLogTimer = null;
            }

            console.log('✅ 所有定时器已停止');
        },

        // 启用轮询 - 已注释
        enablePollingMode() {
            console.log('🔄 启用轮询模式 - 已注释，不执行');
            // this.enablePolling = true;
            // this.forceDisablePolling = false;
            // this.pollingDisabledByUser = false;

            // // 启动数据更新
            // this.startDataUpdate();

            // // 启动加速度轮询
            // if (this.accelerationTimer) {
            //     clearInterval(this.accelerationTimer);
            // }
            // this.accelerationTimer = setInterval(() => {
            //     this.updateAccelerationChart();
            // }, 5000);

            // console.log('✅ 轮询模式已启用');
        },

        // 禁用轮询
        disablePollingMode() {
            console.log('🛑 禁用轮询模式');
            this.enablePolling = false;
            this.forceDisablePolling = true;
            this.pollingDisabledByUser = true;

            // 停止所有定时器
            this.stopAllTimers();

            console.log('✅ 轮询模式已禁用');
        },

        // 修改数据更新方法
        async getList() {
            try {
                this.dataStatus.updating = true;
                const res = await getStatus();

                if (res.code === 200) {
                    // 保存旧的设备数据用于比较
                    const oldDeviceStatusData = [...this.deviceStatusData];

                    // 将接口数据保存到 deviceStatusData
                    this.deviceStatusData = res.data;

                    // 动态更新 latheName 映射
                    this.updateLatheNameMapping(this.deviceStatusData);

                    // 监听 latheName 变化
                    this.handleLatheNameChanges(this.deviceStatusData, oldDeviceStatusData);

                    // 优化：使用 Map 提高性能，减少对象查找开销
                    const latheNameGroupsMap = new Map();

                    // 批量处理设备数据，减少重复操作
                    for (const device of this.deviceStatusData) {
                        if (device.latheName) {
                            if (!latheNameGroupsMap.has(device.latheName)) {
                                latheNameGroupsMap.set(device.latheName, {
                                    devices: [],
                                    status: '离线',
                                    collectTime: device.collectTime
                                });
                            }

                            const group = latheNameGroupsMap.get(device.latheName);
                            group.devices.push(device);

                            // 记录最新的时间
                            if (new Date(device.collectTime) > new Date(group.collectTime)) {
                                group.collectTime = device.collectTime;
                            }

                            // 标准化设备状态
                            const normalizedStatus = this.normalizeDeviceStatus(device.status);

                            // 按优先级更新状态: 故障 > 正常 > 待机 > 离线
                            if (normalizedStatus === '故障') {
                                group.status = '故障';
                            } else if (normalizedStatus === '正常' && group.status !== '故障') {
                                group.status = '正常';
                            } else if (normalizedStatus === '待机' &&
                                      group.status !== '故障' &&
                                      group.status !== '正常') {
                                group.status = '待机';
                            } else if (group.status === '离线' && normalizedStatus === '离线') {
                                // 保持离线状态
                                group.status = '离线';
                            }
                        }
                    }

                    // 转换Map回对象格式
                    const latheNameGroups = Object.fromEntries(latheNameGroupsMap);

                    // 更新latheNameSummaries
                    this.latheNameSummaries = {}; // 清空旧数据
                    Object.keys(latheNameGroups).forEach(latheName => {
                        this.latheNameSummaries[latheName] = {
                            status: latheNameGroups[latheName].status,
                            collectTime: latheNameGroups[latheName].collectTime,
                            // 如果需要，还可以存储其他聚合信息，例如该latheName下的设备ID列表
                            // deviceIds: latheNameGroups[latheName].devices.map(d => d.deviceId)
                        };
                    });

                    // 统计各状态设备数量
                    const stats = {
                        normal: 0,  // 正常
                        warning: 0, // 故障
                        waiting: 0, // 待机
                        offline: 0  // 离线
                    };

                    // 遍历每个latheName设备组，统计状态
                    Object.values(latheNameGroups).forEach(latheData => {
                        switch (latheData.status) {
                            case '正常':
                                stats.normal++;
                                break;
                            case '故障':
                                stats.warning++;
                                break;
                            case '待机':
                                stats.waiting++;
                                break;
                            default:
                                stats.offline++;
                                break;
                        }
                    });

                    // 注释掉动态更新设备总数的代码，保持设备总数为固定值35
                    // const totalLatheNames = Object.keys(latheNameGroups).length;
                    // if (totalLatheNames > 0) {
                    //     this.totalDevices = totalLatheNames;
                    // }

                    // 计算离线设备数量 - 总设备数保持固定为35
                    stats.offline = this.totalDevices - (stats.normal + stats.warning + stats.waiting);

                    // 更新设备状态统计
                    this.deviceStatus = {
                        normalCount: stats.normal,
                        normalRate: Math.round((stats.normal / this.totalDevices) * 100),
                        warningCount: stats.warning,
                        warningRate: Math.round((stats.warning / this.totalDevices) * 100),
                        waitingCount: stats.waiting,
                        waitingRate: Math.round((stats.waiting / this.totalDevices) * 100),
                        offlineCount: stats.offline,
                        offlineRate: Math.round((stats.offline / this.totalDevices) * 100)
                    };

                    // 更新圆环进度条
                    this.updateCircleProgress();

                    // 不再在此处更新监测记录
                    // this.updateMonitorLog(latheNameGroups);

                    // 更新最后更新时间
                    this.dataStatus.lastUpdate = new Date().toLocaleTimeString();

                    // 更新健康评分
                    this.healthScore = this.calculateHealthScore(latheNameGroups);

                    // 图表更新由组件自己管理
                }
            } catch (error) {
                console.error('获取设备状态失败:', error);
            } finally {
                this.dataStatus.updating = false;
            }
        },
// 计算使用率数据
// 计算仪表盘值
// 更新监控日志 - 基于latheName
      getDeviceStatus(deviceId) {
            const device = this.deviceStatusData.find(d => d.deviceId === deviceId);
            if (!device) return '离线';
            return device.status || '离线';
        },
      initCharts() {
            this.$nextTick(() => {
                try {
                    // 使用率曲线图表由组件自己管理

                    // 加速度图表初始化由组件自己管理
                    // 立即获取并更新加速度数据
                    this.updateAccelerationChart()

                    // 注释掉定时更新
                    // if (!this.accelerationTimer) {
                    //     this.accelerationTimer = setInterval(() => {
                    //         this.updateAccelerationChart();
                    //     }, 2000);
                    // }

                    // 添加窗口大小变化监听
                    window.addEventListener('resize', this.handleResize);

                    // 运行率图表由组件自己管理

                    // 删除以下开工率图表初始化代码
                    // if (!this.shiftRateChart && document.getElementById('shiftRateChart')) {
                    //     this.shiftRateChart = echarts.init(document.getElementById('shiftRateChart'))
                    //     this.initShiftRateChart()
                    // }

                    if (!this.comparisonChart && document.getElementById('comparisonChart')) {
                        this.comparisonChart = echarts.init(document.getElementById('comparisonChart'))
                        this.initSensorStatusChart()
                    }
                } catch (error) {
                    console.error('初始化图表失败:', error);
                }
            });
        },
        handleResize() {
            // 图表 resize 由各个组件自己管理
            if (this.comparisonChart) {
                this.comparisonChart.resize()
            }
        },
        // 修改 updateAccelerationChart 方法
        async updateAccelerationChart() {
            try {
                const res = await getAccelerationData();

                if (res.code === 200) {
                    // 获取当前选中的位置，以便在更新后恢复
                    const currentSelectedPosition = this.currentPosition;

                    // 初始化映射关系
                    this.latheNameToDeviceMap = {};

                    // 首先处理latheName的映射关系
                    res.data.forEach(deviceData => {
                        if (deviceData.latheName) {
                            // 确保每个latheName对应的设备ID数组存在
                            if (!this.latheNameToDeviceMap[deviceData.latheName]) {
                                this.latheNameToDeviceMap[deviceData.latheName] = [];
                            }

                            // 添加设备ID到对应的latheName下
                            if (!this.latheNameToDeviceMap[deviceData.latheName].includes(deviceData.deviceId)) {
                                this.latheNameToDeviceMap[deviceData.latheName].push(deviceData.deviceId);
                            }
                        }
                    });

                    // 确保所有DevicesId中的设备都被映射到某个latheName
                    this.DevicesId.forEach(deviceId => {
                        // 检查此设备是否已经在latheNameToDeviceMap中
                        let found = false;
                        for (const latheName in this.latheNameToDeviceMap) {
                            if (this.latheNameToDeviceMap[latheName].includes(deviceId)) {
                                found = true;
                                break;
                            }
                        }

                        // 如果未在任何latheName中找到，添加到默认latheName
                        if (!found) {
                            const defaultName = this.getDeviceName(deviceId);
                            if (!this.latheNameToDeviceMap[defaultName]) {
                                this.latheNameToDeviceMap[defaultName] = [];
                            }
                            this.latheNameToDeviceMap[defaultName].push(deviceId);
                        }
                    });

                    // 提取唯一的latheName列表（保持稳定排序）
                    this.updateUniqueLatheNamesStable();

                    // 仅处理当前设备的数据，避免大规模预分配
                    const currentDeviceData = res.data.find(item => item.deviceId === this.currentDevice.id);

                    if (currentDeviceData) {
                        // 仅为当前设备初始化数据结构（如果尚未存在）
                        if (!this.deviceAccelerationData[this.currentDevice.id]) {
                            await this.initializeDeviceDataOnDemand(this.currentDevice.id);
                        }
                    }

                    // 更新映射关系（轻量级操作）
                    res.data.forEach(deviceData => {
                        const deviceId = deviceData.deviceId;

                        // 仅更新已存在设备的元数据，不创建新的大数组

                        // 更新设备的加速度数据
                        const deviceAccData = this.deviceAccelerationData[deviceId];

                        // 更新设备名称，但不覆盖安装位置（如果当前设备已选择特定位置）
                        if (deviceData.latheName) {
                            deviceAccData.latheName = deviceData.latheName;
                        }

                        // 只有当不是当前选中的设备时，才更新putPlace
                        if (deviceId !== this.currentDevice.id) {
                            if (deviceData.putPlace) {
                                deviceAccData.putPlace = deviceData.putPlace;
                            }
                        }

                        if (deviceData.deviceLocation) {
                            deviceAccData.deviceLocation = deviceData.deviceLocation;
                        }
                        if (deviceData.bindLocation) {
                            deviceAccData.bindLocation = deviceData.bindLocation;
                        }

                        // 检查是否需要更新数据点
                        const now = Date.now();
                        const timeSinceLastUpdate = now - (deviceAccData.lastUpdateTime || 0);

                        // 如果距离上次更新超过5秒或者是首次更新，则添加新的数据点并实现左移效果
                        if (timeSinceLastUpdate >= 5000 || !deviceAccData.lastUpdateTime) {
                            // 更新时间数据 - 整体左移
                            for (let i = 0; i < 59; i++) {
                                deviceAccData.timeData[i] = deviceAccData.timeData[i + 1];
                            }
                            // 添加最新时间点
                            const currentTime = new Date();
                            deviceAccData.timeData[59] = currentTime.toLocaleTimeString('zh-CN', {
                                hour: '2-digit',
                                minute: '2-digit',
                                second: '2-digit' // 添加秒显示
                            });

                            // RMS数据左移并更新最新点
                            for (let i = 0; i < 59; i++) {
                                deviceAccData.rms.x[i] = deviceAccData.rms.x[i + 1];
                                deviceAccData.rms.y[i] = deviceAccData.rms.y[i + 1];
                                deviceAccData.rms.z[i] = deviceAccData.rms.z[i + 1];
                            }

                            // 添加最新RMS数据，使用真实数据
                            deviceAccData.rms.x[59] = deviceData.xrms || 0;
                            deviceAccData.rms.y[59] = deviceData.yrms || 0;
                            deviceAccData.rms.z[59] = deviceData.zrms || 0;

                            // Peak数据左移并更新最新点
                            for (let i = 0; i < 59; i++) {
                                deviceAccData.peak.x[i] = deviceAccData.peak.x[i + 1];
                                deviceAccData.peak.y[i] = deviceAccData.peak.y[i + 1];
                                deviceAccData.peak.z[i] = deviceAccData.peak.z[i + 1];
                            }

                            // 添加最新Peak数据，使用真实数据
                            deviceAccData.peak.x[59] = deviceData.xpeak || 0;
                            deviceAccData.peak.y[59] = deviceData.ypeak || 0;
                            deviceAccData.peak.z[59] = deviceData.zpeak || 0;

                            // 更新最后更新时间
                            deviceAccData.lastUpdateTime = now;
                        } else {
                            // 如果不需要添加新的数据点，只更新最新点的值
                            const lastIndex = 59;

                            // 更新最新点的RMS数据
                            deviceAccData.rms.x[lastIndex] = deviceData.xrms || 0;
                            deviceAccData.rms.y[lastIndex] = deviceData.yrms || 0;
                            deviceAccData.rms.z[lastIndex] = deviceData.zrms || 0;

                            // 更新最新点的Peak数据
                            deviceAccData.peak.x[lastIndex] = deviceData.xpeak || 0;
                            deviceAccData.peak.y[lastIndex] = deviceData.ypeak || 0;
                            deviceAccData.peak.z[lastIndex] = deviceData.zpeak || 0;
                        }

                        // 如果是当前选中的设备，更新设备名称，但保持当前选中的安装位置不变
                        if (deviceId === this.currentDevice.id) {
                            if (deviceData.latheName) {
                                this.currentDevice.latheName = deviceData.latheName;
                                this.currentDevice.name = deviceData.latheName;
                            }

                            // 如果当前没有选择特定位置，但有新的位置信息，则更新
                            if (!this.currentPosition && deviceData.putPlace) {
                                this.currentDevice.putPlace = deviceData.putPlace;
                                this.currentPosition = deviceData.putPlace;
                            } else {
                                // 否则保持当前选择的位置不变
                                this.currentDevice.putPlace = this.currentPosition;
                            }

                            // 避免频繁更新位置列表，仅在必要时更新
                            // this.updateDevicePositions(deviceData.latheName, false);
                        }
                    });

                    // 如果有保存的位置选择，恢复它
                    if (currentSelectedPosition) {
                        this.currentPosition = currentSelectedPosition;
                    }

                    // 安全更新当前选中设备的图表
                    this.$nextTick(() => {
                        // 图表更新由组件自己管理
                    });
                }
            } catch (error) {
                console.error('更新加速度数据失败:', error);
            }
        },
      selectDevice(deviceId) {
            // 保存旧设备ID用于WebSocket处理
            const oldDeviceId = this.currentDevice?.id;

            // 获取当前设备的latheName
            const deviceData = this.deviceAccelerationData[deviceId];
            const latheName = deviceData?.latheName || this.getDeviceName(deviceId);

            // 使用latheName更新当前设备
            this.currentDevice = {
                id: deviceId,
                name: latheName,
                latheName: latheName,
                putPlace: deviceData?.putPlace || '',
            };

            console.log('📱 设备已切换:', this.currentDevice);

            // 处理WebSocket设备切换
            if (this.useWebSocket) {
                this.handleDeviceSwitchForWebSocket(deviceId, oldDeviceId);
            }

            // 图表实例由组件自己管理

            // 重置位置数据
            this.devicePositions = [];
            this.currentPosition = '';

            // Load historical data and then initialize chart
            this.loadHistoricalAccelerationData(deviceId).then(() => {
                // 如果设备有数据且有latheName，获取该latheName下的所有putPlace
                if (latheName && this.hasDeviceData(deviceId)) {
                    this.updateDevicePositions(latheName);
                } else {
                    // 否则直接获取该设备的位置数据
                    getAccelerationData().then(res => {
                        if (res.code === 200) {
                            const deviceDataList = res.data.filter(item => item.deviceId === deviceId);

                            if (deviceDataList.length > 0) {
                                // 更新latheName，然后通过latheName获取putPlace列表
                                const fetchedLatheName = deviceDataList[0].latheName;
                                if (fetchedLatheName) {
                                    this.currentDevice.latheName = fetchedLatheName;
                                    this.currentDevice.name = fetchedLatheName;
                                    this.updateDevicePositions(fetchedLatheName);
                                } else {
                                    // 如果没有latheName，则直接提取putPlace
                                    const positions = new Set();
                                    deviceDataList.forEach(item => {
                                        if (item.putPlace && typeof item.putPlace === 'string') {
                                            positions.add(item.putPlace);
                                        }
                                    });

                                    this.devicePositions = Array.from(positions);

                                    if (this.devicePositions.length > 0) {
                                        this.currentPosition = this.devicePositions[0];
                                    }
                                }

                                // 更新当前设备putPlace
                                this.currentDevice.putPlace = deviceDataList[0].putPlace || '';
                            }
                        }

                        // 图表初始化由组件自己处理
                    }).catch(error => {
                        console.error('获取设备数据失败:', error);
                        // 图表初始化由组件自己处理
                    });
                }
                this.healthScore = this.calculateHealthScore(); // this was outside, moved in or should be outside?
                                                            // It seems to depend on deviceStatusData not acceleration data directly.
                                                            // Let's assume it can stay where it was or be called after this .then()
            });
            this.healthScore = this.calculateHealthScore(); // Placed here assuming it should run regardless of async history load for chart
        },

// 加速度图表初始化已移动到 AccelerationChart 组件中

        // 计算健康评分 - 基于latheName
        calculateHealthScore(latheNameGroups = null) {
            // 初始分数为100
            let score = 100;
            const details = [];
            let faultCount = 0;

            // 如果没有传入latheName分组，则重新构建
            if (!latheNameGroups) {
                latheNameGroups = {};

                // 按latheName分组统计
                this.deviceStatusData.forEach(device => {
                    if (device.latheName) {
                        if (!latheNameGroups[device.latheName]) {
                            latheNameGroups[device.latheName] = {
                                devices: [device],
                                status: device.status || '离线'
                            };
                        } else {
                            latheNameGroups[device.latheName].devices.push(device);

                            // 按优先级更新状态
                            if (device.status === '故障') {
                                latheNameGroups[device.latheName].status = '故障';
                            } else if (device.status === '正常' && latheNameGroups[device.latheName].status !== '故障') {
                                latheNameGroups[device.latheName].status = '正常';
                            } else if (device.status === '待机' &&
                                      latheNameGroups[device.latheName].status !== '故障' &&
                                      latheNameGroups[device.latheName].status !== '正常') {
                                latheNameGroups[device.latheName].status = '待机';
                            }
                        }
                    }
                });
            }

            // 遍历每个latheName设备组，检查是否有故障
            Object.entries(latheNameGroups).forEach(([latheName, latheData]) => {
                if (latheData.status === '故障') {
                    faultCount++;
                    score = Math.max(0, score - 50); // 每台故障设备扣50分，不低于0分
                    details.push(`设备 ${latheName} 故障 -50分`);
                }
            });

            // 确定健康状态
            let status;
            if (score >= 80) {
                status = 'normal';
            } else if (score >= 50) {
                status = 'warning';
            } else {
                status = 'error';
            }

            // 如果没有故障设备，添加正常运行信息
            if (faultCount === 0) {
                details.push('所有设备运行正常');
            }



            return {
                score,
                details,
                status
            };
        },
      handleImageError(e) {
            console.error('图片加载失败');
            e.target.src = require('../../../assets/detect/offline.png'); // 加载失败时使用离线图标
        },
        toggleFullscreen() {
            if (!document.fullscreenElement) {
                const dashboard = document.querySelector('.dashboard');
                if (dashboard.requestFullscreen) {
                    dashboard.requestFullscreen();
                }
            } else {
                if (document.exitFullscreen) {
                    document.exitFullscreen();
                }
            }
        },
        handleFullscreenChange() {
            this.$nextTick(() => {
                if (this.liquidChart) {
                    const container = document.querySelector('.score-circle');
                    if (container) {
                        // 根据全屏状态设置不同尺寸
                        const size = document.fullscreenElement ? 150 : 120;
                        this.liquidChart.resize({
                            width: size,
                            height: size
                        });
                        // 重新定位图表
                        if (document.fullscreenElement) {
                            container.style.left = '-40px';
                        } else {
                            container.style.left = '0';
                        }
                    }

                }
            });
        },



        switchAccelerationType(type) {
            this.accelerationType = type;

            // 图表刷新由组件自己处理
        },
        // 添加初始化传感器运行状态图表的方法
        initSensorStatusChart() {
            if (!this.comparisonChart) return;

            const option = {
                series: [{
                    type: 'gauge',
                    startAngle: 180,
                    endAngle: 0,
                    min: 0,
                    max: 100,
                    splitNumber: 10,
                    radius: '65%',
                    center: ['30%', '45%'],
                    progress: {
                        show: true,
                        roundCap: true,
                        width: 15,
                        itemStyle: {
                            color: {
                                type: 'linear',
                                x: 0,
                                y: 0,
                                x2: 1,
                                y2: 0,
                                colorStops: [{
                                    offset: 0,
                                    color: '#00ff4c'
                                }, {
                                    offset: 1,
                                    color: '#39ffa1'
                                }]
                            },
                            shadowColor: 'rgba(0, 255, 76, 0.5)',
                            shadowBlur: 10
                        }
                    },
                    pointer: {
                        show: true,
                        length: '60%',
                        width: 3,
                        itemStyle: {
                            color: '#00ff4c',
                            shadowColor: 'rgba(0, 255, 76, 0.5)',
                            shadowBlur: 5
                        }
                    },
                    axisLine: {
                        roundCap: true,
                        lineStyle: {
                            width: 15,
                            color: [
                                [1, {
                                    type: 'linear',
                                    colorStops: [{
                                        offset: 0,
                                        color: 'rgba(0, 255, 76, 0.05)'
                                    }, {
                                        offset: 1,
                                        color: 'rgba(0, 255, 76, 0.1)'
                                    }]
                                }]
                            ]
                        }
                    },
                    axisTick: {
                        show: true,
                        distance: -15,
                        length: 4,
                        lineStyle: {
                            color: '#ffffff',
                            width: 1,
                            opacity: 0.5
                        }
                    },
                    splitLine: {
                        show: true,
                        distance: -15,
                        length: 8,
                        lineStyle: {
                            color: '#ffffff',
                            width: 2,
                            opacity: 0.7
                        }
                    },
                    axisLabel: {
                        show: false
                    },
                    detail: {
                        show: true,
                        position: 'right',
                        offsetCenter: this.isFullscreen ? [200, -30] : [180, -30],  // 全屏时调整位置
                        formatter: function (value) {
                            return [
                                '{title|全力护航}',
                                '{value|' + value + '%}',
                                '{device|传感器：35台}'
                            ].join('\n');
                        },
                        rich: {
                            title: {
                                fontSize: this.isFullscreen ? 22 : 16,  // 全屏时放大字号
                                color: '#fff',
                                padding: [0, 0, 15, 0],
                                fontWeight: 'normal',
                                align: 'left'
                            },
                            value: {
                                fontSize: this.isFullscreen ? 42 : 32,  // 全屏时放大字号
                                fontWeight: 'bold',
                                color: '#fff',
                                padding: [0, 0, 15, 0],
                                align: 'left'
                            },
                            device: {
                                fontSize: this.isFullscreen ? 20 : 14,  // 全屏时放大字号
                                color: '#fff',
                                padding: [0, 0, 0, 0],
                                align: 'left'
                            }
                        }
                    },
                    data: [{
                        value:100,
                        name: ''
                    }]
                }]
            };

            this.comparisonChart.setOption(option);
        },
        // 添加更新圆环进度条的方法
        updateCircleProgress() {
            const progressElement = document.querySelector('.circle-progress');
            if (progressElement) {
                // 设置CSS变量来控制圆环显示
                progressElement.style.setProperty('--normal-rate', this.deviceStatus.normalRate);
                progressElement.style.setProperty('--warning-rate', this.deviceStatus.warningRate);
                progressElement.style.setProperty('--waiting-rate', this.deviceStatus.waitingRate);
                // 离线率会自动填充剩余部分
            }
        },
        getStatusClass(status) {
            switch (status) {
                case '正常':
                    return 'normal';
                case '待机':
                    return 'waiting';
                case '故障':
                    return 'warning';
                default:
                    return 'offline';
            }
        },


        switchWorkshop(workshopId) {
            this.currentWorkshop = workshopId;
            // 这里可以添加切换车间后的其他逻辑
        },

        // 轻量级预加载：仅建立映射关系，不预分配大数组
        async prefetchAccelerationDataLightweight() {
            try {
                const res = await getAccelerationData();

                if (res.code === 200 && Array.isArray(res.data)) {
                    // 初始化映射
                    this.latheNameToDeviceMap = {};

                    // 处理latheName的映射关系
                    res.data.forEach(deviceData => {
                        if (deviceData.latheName) {
                            if (!this.latheNameToDeviceMap[deviceData.latheName]) {
                                this.latheNameToDeviceMap[deviceData.latheName] = [];
                            }
                            if (!this.latheNameToDeviceMap[deviceData.latheName].includes(deviceData.deviceId)) {
                                this.latheNameToDeviceMap[deviceData.latheName].push(deviceData.deviceId);
                            }
                        }
                    });

                    // 确保所有DevicesId中的设备都被映射到某个latheName
                    this.DevicesId.forEach(deviceId => {
                        let found = false;
                        for (const latheName in this.latheNameToDeviceMap) {
                            if (this.latheNameToDeviceMap[latheName].includes(deviceId)) {
                                found = true;
                                break;
                            }
                        }

                        if (!found) {
                            const defaultName = this.getDeviceName(deviceId);
                            if (!this.latheNameToDeviceMap[defaultName]) {
                                this.latheNameToDeviceMap[defaultName] = [];
                            }
                            this.latheNameToDeviceMap[defaultName].push(deviceId);
                        }
                    });

                    // 提取唯一的latheName列表（保持稳定排序）
                    this.updateUniqueLatheNamesStable();

                    // 提取位置数据（仅收集，不预分配设备数据）
                    const positions = new Set();
                    res.data.forEach(item => {
                        if (item.putPlace && typeof item.putPlace === 'string') {
                            positions.add(item.putPlace);
                        }
                    });

                    this.devicePositions = Array.from(positions);
                    if (this.devicePositions.length > 0) {
                        this.currentPosition = this.devicePositions[0];
                    }

                    console.log('✅ 轻量级预加载完成，设备映射:', Object.keys(this.latheNameToDeviceMap).length);
                }
            } catch (error) {
                console.error('轻量级预加载失败:', error);
            }
        },

        // 统一的非关键数据异步初始化（避免分散的卡顿）
        async initializeNonCriticalDataAsync() {
            console.log('🔄 开始统一初始化非关键数据...');

            try {
                // 谨慎恢复WebSocket，使用超强性能优化
                await this.executeWithTimeSlicing([
                    () => this.initializeWebSocketWithPerformanceOptimization(), // 使用优化版WebSocket
                    () => this.loadCurrentDeviceDataAsync(),
                    () => this.initializeAdditionalDataLightweight() // 恢复检测记录初始化
                ]);

                console.log('✅ 非关键数据初始化完成');
            } catch (error) {
                console.error('❌ 非关键数据初始化失败:', error);
            }
        },

        // 时间切片执行器（优化版本：更短的间隔）
        async executeWithTimeSlicing(tasks) {
            for (let i = 0; i < tasks.length; i++) {
                const task = tasks[i];
                const startTime = performance.now();

                // 执行任务
                await task();

                const executionTime = performance.now() - startTime;
                console.log(`📊 任务 ${i + 1}/${tasks.length} 执行完成，耗时: ${executionTime.toFixed(2)}ms`);

                // 每个任务后让出控制权，使用更短的间隔
                if (i < tasks.length - 1) {
                    await new Promise(resolve => setTimeout(resolve, 50)); // 减少到50ms
                }
            }
        },

        // 轻量级的附加数据初始化
        async initializeAdditionalDataLightweight() {
            console.log('🔄 开始轻量级附加数据初始化...');

            try {
                // 仅执行必要的数据关联，跳过重复的网络请求
                this.associateStatusAndAcceleration();
                console.log('✅ 轻量级附加数据初始化完成');
            } catch (error) {
                console.error('❌ 轻量级附加数据初始化失败:', error);
            }
        },

        // 异步加载当前设备的详细数据（按需分配）
        async loadCurrentDeviceDataAsync() {
            if (!this.currentDevice || !this.currentDevice.id) return;

            console.log('📊 开始异步加载当前设备数据:', this.currentDevice.id);

            try {
                // 仅为当前设备初始化数据结构
                await this.initializeDeviceDataOnDemand(this.currentDevice.id);

                // 加载历史数据
                await this.loadHistoricalAccelerationData(this.currentDevice.id);

                // 避免在异步加载时频繁更新位置信息
                // if (this.currentDevice.latheName) {
                //     await this.updateDevicePositions(this.currentDevice.latheName);
                // }

                console.log('✅ 当前设备数据加载完成');
            } catch (error) {
                console.error('❌ 当前设备数据加载失败:', error);
            }
        },

        // 按需初始化设备数据（仅当前设备，60点而非300点）
        async initializeDeviceDataOnDemand(deviceId) {
            if (this.deviceAccelerationData[deviceId]) {
                return; // 已存在，跳过
            }

            // 创建60个点的时间数组（而非300个）
            const timePoints = Array(60).fill('').map((_, index) => {
                const time = new Date(Date.now() - (59 - index) * 10000); // 10秒间隔
                return time.toLocaleTimeString('zh-CN', {
                    hour: '2-digit',
                    minute: '2-digit',
                    second: '2-digit'
                });
            });

            // 仅为当前设备分配数据结构
            this.deviceAccelerationData[deviceId] = {
                latheName: this.currentDevice.latheName || '',
                putPlace: this.currentDevice.putPlace || '',
                deviceLocation: '',
                bindLocation: '',
                rms: {
                    x: Array(60).fill(null), // 60点而非300点
                    y: Array(60).fill(null),
                    z: Array(60).fill(null)
                },
                peak: {
                    x: Array(60).fill(null),
                    y: Array(60).fill(null),
                    z: Array(60).fill(null)
                },
                timeData: timePoints,
                lastUpdateTime: Date.now()
            };

            console.log(`📊 按需初始化设备 ${deviceId} 数据结构（60点）`);
        },

        // 稳定更新uniqueLatheNames，避免设备位置跳动
        updateUniqueLatheNamesStable() {
            const newUniqueLatheNames = Object.keys(this.latheNameToDeviceMap).sort();

            // 如果是首次初始化，直接设置
            if (this.uniqueLatheNames.length === 0) {
                this.uniqueLatheNames = newUniqueLatheNames;
                console.log('📊 首次初始化设备列表:', this.uniqueLatheNames);
                return;
            }

            // 检查是否有设备被移除
            const currentNames = new Set(newUniqueLatheNames);
            const removedNames = this.uniqueLatheNames.filter(name => !currentNames.has(name));

            // 检查是否有新设备
            const existingNames = new Set(this.uniqueLatheNames);
            const newNames = newUniqueLatheNames.filter(name => !existingNames.has(name));

            // 如果有设备被移除，需要重新排列
            if (removedNames.length > 0) {
                this.uniqueLatheNames = this.uniqueLatheNames.filter(name => currentNames.has(name));
                console.log('📊 移除设备:', removedNames);
            }

            // 如果有新设备，添加到末尾（保持排序）
            if (newNames.length > 0) {
                this.uniqueLatheNames = [...this.uniqueLatheNames, ...newNames.sort()];
                console.log('📊 新增设备:', newNames);
            }

            // 如果没有变化，保持原有顺序不变
            if (removedNames.length === 0 && newNames.length === 0) {
                console.log('📊 设备列表无变化，保持原有位置');
            }
        },
        hasDeviceData(deviceId) {
            // 首先检查设备状态，如果是离线或待机，则直接返回false
            const deviceStatus = this.getDeviceStatus(deviceId);
            if (deviceStatus === '离线' || deviceStatus === '待机') {
                return false;
            }

            // 然后检查deviceAccelerationData是否存在并且数据是否有效
            const deviceData = this.deviceAccelerationData[deviceId];
            if (!deviceData) return false;

            // 检查是否所有数据都是0，如果都是0，可能没有真实数据
            const allZero = (
                deviceData.rms.x.every(val => val === 0) &&
                deviceData.rms.y.every(val => val === 0) &&
                deviceData.rms.z.every(val => val === 0) &&
                deviceData.peak.x.every(val => val === 0) &&
                deviceData.peak.y.every(val => val === 0) &&
                deviceData.peak.z.every(val => val === 0)
            );

            // 只有当状态正常且至少有一个轴有非零数据时，才认为有数据
            return !allZero;
        },
        switchPosition(position) {
            if (this.currentPosition !== position) {
                this.currentPosition = position;
              console.log('筛选后的数据:', position)
                // 更新当前位置的加速度数据
                this.updateAccelerationChartByPosition(); // This might update currentDevice.id
                // this.loadHistoricalAccelerationData(this.currentDevice.id); // Load historical data for the new position/device


            }
        },
        // 根据当前latheName和position筛选加速度数据
        updateAccelerationChartByPosition() {
            const latheName = this.currentDevice.latheName;
            if (!latheName || !this.currentPosition) return;

            getAccelerationData().then(res => {
                if (res.code === 200) {
                    // 筛选当前latheName和当前位置的数据
                    const filteredData = res.data.filter(item =>
                        item.latheName === latheName &&
                        item.putPlace === this.currentPosition
                    );

                    if (filteredData.length > 0) {
                        const deviceData = filteredData[0];
                        console.log('更新当前设备ID和位置:', deviceData)
                        // 如果找到匹配的设备数据，使用该设备进行图表更新
                        if (deviceData.deviceId && deviceData.deviceId !== this.currentDevice.id) {
                            // 更新当前设备ID，但保持latheName和位置不变
                          console.log('更新id:', deviceData.deviceId)

                            this.currentDevice.id = deviceData.deviceId;
                            this.currentDevice.putPlace = this.currentPosition;

                            // 确保数据已加载
                            if (!this.deviceAccelerationData[deviceData.deviceId]) {
                                // 初始化设备数据
                                // 与 updateAccelerationChart 中 timePoints 生成逻辑保持一致
                                const timePoints = Array(60).fill('').map((_, index) => {
                                    const time = new Date(Date.now() - (59 - index) * 10000); // 10秒 = 10000毫秒
                                    return time.toLocaleTimeString('zh-CN', {
                                        hour: '2-digit',
                                        minute: '2-digit',
                                        second: '2-digit'
                                    });
                                });

                                this.deviceAccelerationData[deviceData.deviceId] = {
                                    latheName: latheName,
                                    putPlace: this.currentPosition,
                                    deviceLocation: deviceData.deviceLocation || '',
                                    bindLocation: deviceData.bindLocation || '',
                                    rms: {
                                        x: Array(60).fill(null), // 统一为60点，null填充
                                        y: Array(60).fill(null),
                                        z: Array(60).fill(null)
                                    },
                                    peak: {
                                        x: Array(60).fill(null), // 统一为60点，null填充
                                        y: Array(60).fill(null),
                                        z: Array(60).fill(null)
                                    },
                                    timeData: timePoints, // 使用统一的时间点生成
                                    lastUpdateTime: Date.now()
                                };
                            }
                        }
                    }
                }
              // 重新初始化图表
              this.loadHistoricalAccelerationData(this.currentDevice.id);
            }).catch(error => {
                console.error('获取位置加速度数据失败:', error);
            });
        },
        // 获取设备安装位置数据
        async fetchDevicePositions() {
            try {
                const res = await getAccelerationData();

                if (res.code === 200 && Array.isArray(res.data)) {
                    // 只获取当前设备的数据
                    const currentDeviceData = res.data.filter(item =>
                        item.deviceId === this.currentDevice.id
                    );

                    // 只有当设备状态正常且有数据时才提取位置信息
                    if (currentDeviceData.length > 0 && this.hasDeviceData(this.currentDevice.id)) {
                        // 从响应中提取putPlace数据
                        const positions = new Set(); // 使用Set去重

                        currentDeviceData.forEach(item => {
                            if (item.putPlace && typeof item.putPlace === 'string') {
                                positions.add(item.putPlace);
                            }
                        });

                        // 转换为数组
                        this.devicePositions = Array.from(positions);

                        // 如果有位置数据，且当前没有选择的位置，则默认选中第一个
                        if (this.devicePositions.length > 0 && !this.currentPosition) {
                            this.currentPosition = this.devicePositions[0];
                        }

                        console.log('获取到设备安装位置：', this.devicePositions);
                    } else {
                        // 如果设备离线或待机，清空位置数据
                        this.devicePositions = [];
                        this.currentPosition = '';
                    }
                }
            } catch (error) {
                console.error('获取设备安装位置失败:', error);
                this.devicePositions = [];
                this.currentPosition = '';
            }
        },

        // 初始化其他相关数据（检测记录、设备状态、使用率统计）
        async initializeAdditionalData() {
            console.log('🔄 开始初始化其他相关数据...');

            try {
                // 并行获取多个数据源
                const [statusData, detectionRecords, usageStats] = await Promise.allSettled([
                    this.fetchDeviceStatus(),
                    this.fetchDetectionRecords(),
                    this.fetchUsageStatistics()
                ]);

                // 处理设备状态数据
                if (statusData.status === 'fulfilled') {
                    console.log('✅ 设备状态数据获取成功');
                } else {
                    console.error('❌ 设备状态数据获取失败:', statusData.reason);
                }

                // 处理检测记录数据
                if (detectionRecords.status === 'fulfilled') {
                    console.log('✅ 检测记录数据获取成功');
                } else {
                    console.error('❌ 检测记录数据获取失败:', detectionRecords.reason);
                }

                // 处理使用率统计数据
                if (usageStats.status === 'fulfilled') {
                    console.log('✅ 使用率统计数据获取成功');
                } else {
                    console.error('❌ 使用率统计数据获取失败:', usageStats.reason);
                }

                // 数据映射和关联
                this.mapAndAssociateData();

                console.log('✅ 其他数据初始化完成');

            } catch (error) {
                console.error('❌ 初始化其他数据时出错:', error);
                throw error;
            }
        },

        // 获取设备状态数据（复用现有的getList方法，避免重复请求）
        async fetchDeviceStatus() {
            console.log('📊 获取设备状态数据（复用getList方法）...');

            try {
                // 直接调用现有的getList方法，它已经调用了getStatus()接口
                // 并且已经包含了完整的设备状态统计逻辑
                await this.getList();

                // getList方法已经更新了deviceStatusData和deviceStatus统计
                if (this.deviceStatusData && Array.isArray(this.deviceStatusData)) {
                    console.log('✅ 设备状态数据处理完成，设备数量:', this.deviceStatusData.length);
                    console.log('✅ 设备状态统计:', this.deviceStatus);
                    return this.deviceStatusData;
                } else {
                    console.warn('⚠️ 设备状态数据为空');
                    return [];
                }
            } catch (error) {
                console.error('❌ 获取设备状态数据失败:', error);
                throw error;
            }
        },

        // 获取检测记录数据（基于现有接口生成）
        async fetchDetectionRecords() {
            console.log('📋 获取检测记录数据（基于设备状态生成）...');

            try {
                let records = [];

                // 由于后端没有检测记录列表接口，直接使用设备状态数据生成检测记录
                if (this.deviceStatusData && Array.isArray(this.deviceStatusData)) {
                    records = this.generateDetectionRecordsFromStatus(this.deviceStatusData);
                    console.log('✅ 从设备状态数据生成检测记录:', records.length, '条');
                } else {
                    // 如果没有设备状态数据，生成默认检测记录
                    records = this.generateDefaultDetectionRecords();
                    console.log('✅ 生成默认检测记录:', records.length, '条');
                }

                // 处理检测记录数据
                this.processDetectionRecords(records);

                console.log('✅ 检测记录数据处理完成，记录数量:', records.length);
                return records;

            } catch (error) {
                console.error('❌ 获取检测记录数据失败:', error);

                // 生成默认的检测记录
                const defaultRecords = this.generateDefaultDetectionRecords();
                this.processDetectionRecords(defaultRecords);

                return defaultRecords;
            }
        },

        // 获取使用率统计数据
        async fetchUsageStatistics() {
            console.log('📈 获取使用率统计数据...');

            try {
                // 这里可能需要调用专门的统计接口
                // 暂时使用设备检测信息来计算使用率
                const res = await getDetectInfo();

                if (res.code === 200) {
                    const data = res.data || [];

                    // 处理使用率统计
                    this.processUsageStatistics(data);

                    console.log('✅ 使用率统计数据处理完成');
                    return data;
                } else {
                    console.error('❌ 使用率统计数据格式错误:', res);
                    return [];
                }
            } catch (error) {
                console.error('❌ 获取使用率统计数据失败:', error);
                throw error;
            }
        },

        getDeviceName(deviceId) {
            // 优先使用加速度数据中的latheName
            if (this.deviceAccelerationData[deviceId]?.latheName) {
                return this.deviceAccelerationData[deviceId].latheName;
            }

            // 其次在设备状态数据中查找
            const device = this.deviceStatusData.find(d => d.deviceId === deviceId);
            if (device && device.latheName) {
                return device.latheName;
            }

            // 如果latheName为空，则使用Junker磨床+序号格式
            const idStr = String(deviceId);
            const suffix = idStr.length >= 4 ? idStr.slice(-4) : idStr;
            return `磨床${suffix}`;
        },



        // 处理检测记录数据
        processDetectionRecords(records) {
            console.log('📋 处理检测记录数据...');

            if (!Array.isArray(records)) {
                console.warn('⚠️ 检测记录数据格式错误');
                return;
            }

            // 处理检测记录，生成监控日志格式
            const processedLogs = records.map(record => {
                const normalizedStatus = this.normalizeDeviceStatus(record.status);
                return {
                    id: record.id || Date.now() + Math.random(),
                    deviceName: record.latheName || record.deviceName || '未知设备',
                    deviceId: record.deviceId,
                    status: normalizedStatus, // 使用标准化状态
                    message: record.message || this.generateLogMessage({
                        ...record,
                        status: normalizedStatus
                    }),
                    timestamp: record.createTime || record.timestamp || new Date().toISOString(),
                    level: this.getLogLevel(normalizedStatus),
                    type: normalizedStatus, // MonitorLog组件使用type字段显示状态
                    time: this.formatLogTime(record.createTime || record.timestamp || new Date().toISOString())
                };
            });

            // 更新监控日志
            this.monitorLogs = processedLogs.slice(0, 8); // 只显示最近8条

            console.log('✅ 检测记录处理完成，记录数量:', processedLogs.length);
            console.log('处理后的日志示例:', processedLogs[0]);
        },

        // 处理使用率统计数据
        processUsageStatistics(data) {
            console.log('📈 处理使用率统计数据...');

            if (!Array.isArray(data)) {
                console.warn('⚠️ 使用率统计数据格式错误');
                return;
            }

            // 计算设备使用率
            const usageRates = this.calculateDeviceUsageRates(data);

            // 更新运行率数据
            this.runningRates = usageRates;

            console.log('✅ 使用率统计处理完成:', usageRates);
        },

        // 数据映射和关联
        mapAndAssociateData() {
            console.log('🔗 开始数据映射和关联...');

            try {
                // 1. 关联设备状态和加速度数据
                this.associateStatusAndAcceleration();

                // 2. 更新设备映射关系
                this.updateDeviceMapping();

                // 3. 生成综合监控日志
                this.generateComprehensiveMonitorLogs();

                console.log('✅ 数据映射和关联完成');

            } catch (error) {
                console.error('❌ 数据映射和关联失败:', error);
            }
        },

        // 添加一个方法用于根据latheName更新设备的putPlace列表（带防抖）
        updateDevicePositions(latheName, autoSelectFirst = true) {
            if (!latheName) return;

            // 防抖：避免短时间内重复调用
            const debounceKey = `updatePositions_${latheName}`;
            const now = Date.now();
            const lastCall = this._positionUpdateTimes?.[debounceKey] || 0;

            if (now - lastCall < 2000) { // 2秒防抖
                console.log(`⏱️ 位置更新防抖：${latheName}`);
                return;
            }

            if (!this._positionUpdateTimes) {
                this._positionUpdateTimes = {};
            }
            this._positionUpdateTimes[debounceKey] = now;

            // 获取设备位置数据
            getAccelerationData().then(res => {
                if (res.code === 200) {
                    // 筛选具有相同latheName的所有设备数据
                    const sameLatheDevices = res.data.filter(item => item.latheName === latheName);

                    if (sameLatheDevices.length > 0) {
                        // 提取位置信息
                        const positions = new Set();
                        sameLatheDevices.forEach(item => {
                            if (item.putPlace && typeof item.putPlace === 'string') {
                                positions.add(item.putPlace);
                            }
                        });

                        const newPositions = Array.from(positions);

                        // 仅在位置列表真正发生变化时才更新
                        if (JSON.stringify(this.devicePositions) !== JSON.stringify(newPositions)) {
                            this.devicePositions = newPositions;
                            console.log(`📍 位置列表已更新 ${latheName}:`, this.devicePositions);

                            // 如果有位置数据，且需要自动选择第一个位置，并且当前没有选择的位置
                            if (this.devicePositions.length > 0 && autoSelectFirst && !this.currentPosition) {
                                this.currentPosition = this.devicePositions[0];
                                console.log(`📍 自动选择位置:`, this.currentPosition);
                            }
                        }
                    }
                }
            }).catch(error => {
                console.error('获取设备位置数据失败:', error);
            });
        },
        getLatheNameStatus(latheName) {
            if (!latheName || !this.latheNameToDeviceMap[latheName]) {
                return '离线';
            }

            // 检查是否为没有真实latheName而自动生成的名称
            // 如果是通过getDeviceName方法生成的名称格式(磨床+数字)，且设备没有实际数据，则显示为离线
            if (latheName.match(/^磨床\d+$/) && !this.deviceHasRealLatheName(latheName)) {
                return '离线';
            }

            const deviceIds = this.latheNameToDeviceMap[latheName];
            let status = '离线';

            // 优先级：故障 > 正常 > 待机 > 离线
            for (const deviceId of deviceIds) {
                const deviceStatus = this.getDeviceStatus(deviceId);
                if (deviceStatus === '故障') {
                    return '故障'; // 如果有任何设备故障，立即返回故障状态
                } else if (deviceStatus === '正常' && status !== '故障') {
                    status = '正常'; // 如果有设备正常，且当前没有故障状态，设为正常
                } else if (deviceStatus === '待机' && status === '离线') {
                    status = '待机'; // 如果有设备待机，且当前为离线状态，设为待机
                }
            }

            return status;
        },
        getLatheNameIcon(latheName) {
            const status = this.getLatheNameStatus(latheName);
            const iconMap = {
                '正常': require('../../../assets/detect/normal.png'),
                '故障': require('../../../assets/detect/warning.png'),
                '待机': require('../../../assets/detect/waiting.png'),
                '离线': require('../../../assets/detect/offline.png')
            };
            return iconMap[status] || require('../../../assets/detect/offline.png');
        },
        selectLatheNameDevice(latheName) {
            if (!latheName || !this.latheNameToDeviceMap[latheName]) {
                return;
            }

            // 从该latheName下获取一个有效的设备ID
            const deviceIds = this.latheNameToDeviceMap[latheName];
            let selectedDeviceId = deviceIds[0]; // 默认选择第一个

            // 优先选择状态为正常的设备
            for (const deviceId of deviceIds) {
                const deviceStatus = this.getDeviceStatus(deviceId);
                if (deviceStatus === '正常') {
                    selectedDeviceId = deviceId;
                    break;
                }
            }

            // 调用现有的selectDevice方法
            this.selectDevice(selectedDeviceId);
        },
// 检查设备是否有真实的latheName（非自动生成）
        deviceHasRealLatheName(latheName) {
            // 如果latheName不存在于latheNameToDeviceMap中，说明不是真实latheName
            if (!this.latheNameToDeviceMap[latheName]) {
                return false;
            }

            // 获取该latheName下的所有设备ID
            const deviceIds = this.latheNameToDeviceMap[latheName];

            // 检查是否有任何设备在加速度数据中有真实的latheName
            for (const deviceId of deviceIds) {
                // 如果在设备加速度数据中能找到相同的latheName，说明这是一个真实的latheName
                if (this.deviceAccelerationData[deviceId]?.latheName === latheName) {
                    // 进一步确认这个latheName不是通过getDeviceName自动生成的
                    const device = this.deviceStatusData.find(d => d.deviceId === deviceId);
                    if (device && device.latheName === latheName) {
                        return true;
                    }
                }
            }

            // 如果没有找到匹配的真实latheName，返回false
            return false;
        },
        // 启动监测记录轮播（轻量化版本）
        startMonitorLogCarousel() {
            console.log('🔄 启动轻量化监测记录轮播...');

            if (this.monitorLogTimer) {
                clearInterval(this.monitorLogTimer);
            }

            // 延迟启动，避免页面初始化时的负载
            setTimeout(() => {
                // 首次更新
                this.updateMonitorLogCarouselLightweight();

                // 设置更长的轮播间隔，减少频率
                this.monitorLogTimer = setInterval(() => {
                    this.updateMonitorLogCarouselLightweight();
                }, 120000); // 2分钟轮播一次，减少频率
            }, 8000); // 延迟8秒启动，确保页面完全稳定
        },

        // 轻量化版本：最小化计算，避免性能问题
        updateMonitorLogCarouselLightweight() {
            if (this.uniqueLatheNames.length === 0) {
                this.monitorLogs = [];
                return;
            }

            console.log('📊 轻量化监测记录更新...');
            const startTime = performance.now();

            // 仅处理前6个设备，进一步减少计算量
            const maxDevices = Math.min(6, this.uniqueLatheNames.length);
            const deviceBatch = this.uniqueLatheNames.slice(0, maxDevices);

            // 简化数据生成，避免复杂计算
            const logs = deviceBatch.map((latheName, index) => {
                const summary = this.latheNameSummaries[latheName];
                const status = summary ? summary.status : '离线';

                // 使用简化的时间格式
                const now = new Date();
                const time = `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`;

                return {
                    deviceName: latheName,
                    time: time,
                    type: status,
                    isNewAlarm: false // 简化，不检查新告警
                };
            });

            this.monitorLogs = logs;

            const processingTime = performance.now() - startTime;
            console.log(`📊 轻量化监测记录更新完成，耗时: ${processingTime.toFixed(2)}ms`);
        },

        // 优化版本：极简化计算，最小化性能开销
        updateMonitorLogCarouselOptimized() {
            if (this.uniqueLatheNames.length === 0) {
                this.monitorLogs = [];
                this.newlyFaultyLatheNames.clear();
                return;
            }

            // 使用时间切片，分批处理，避免长时间阻塞
            const performUpdate = () => {
                const startTime = performance.now();

                // 仅处理前8个设备，减少计算量
                const maxDevices = Math.min(8, this.uniqueLatheNames.length);
                const deviceBatch = this.uniqueLatheNames.slice(0, maxDevices);

                const logs = deviceBatch.map(latheName => {
                    const summary = this.latheNameSummaries[latheName];
                    const status = summary ? summary.status : '离线';
                    const collectTime = summary ? summary.collectTime : new Date().toISOString();

                    return {
                        deviceName: latheName,
                        time: new Date(collectTime).toLocaleTimeString('zh-CN', {
                            hour: '2-digit',
                            minute: '2-digit'
                        }),
                        type: status,
                        isNewAlarm: false // 简化，不检查新告警
                    };
                });

                this.monitorLogs = logs;

                const processingTime = performance.now() - startTime;
                console.log(`📊 监测记录更新完成，耗时: ${processingTime.toFixed(2)}ms`);
            };

            // 使用 setTimeout 避免阻塞，简化异步处理
            setTimeout(performUpdate, 0);
        },

        // 保留原方法作为备用
        updateMonitorLogCarousel() {
            // 原实现保持不变，作为备用方案
            /*
            this.$nextTick(() => {
                const logListElement = this.$el.querySelector('.log-list');
                if (logListElement) {
                    logListElement.scrollTop = 0;
                }
            });
            */
        },
        startAutoDeviceHover() {
            // 注释掉自动设备悬浮
            // this.stopAutoDeviceHover(); // 先清除已有的定时器
            // if (this.uniqueLatheNames && this.uniqueLatheNames.length > 0) {
            //     // 立即显示下一个（或第一个）
            //     this.showNextAutoHoveredDevice();

            //     // 启动增强版的轮播间隔
            //     this.autoHoverTimer = setInterval(() => {
            //         // 如果有故障设备，减少轮播间隔以更频繁展示故障设备
            //         const hasWarning = Object.values(this.latheNameSummaries).some(summary =>
            //             summary && summary.status === '故障'
            //         );

            //         // 根据是否有故障设备动态调整间隔
            //         if (hasWarning) {
            //             // 在有故障设备时，调整为更短的间隔（3秒）
            //             this.autoHoverInterval = 3000;
            //         } else {
            //             // 在无故障设备时，恢复默认间隔（5秒）
            //             this.autoHoverInterval = 5000;
            //         }

            //         this.showNextAutoHoveredDevice();
            //     }, this.autoHoverInterval);
            // }
        },
        showNextAutoHoveredDevice()
        {
          if (!this.uniqueLatheNames || this.uniqueLatheNames.length === 0) {
            this.autoHoverDeviceName = null;
            return;
          }

          // 先清除当前的悬浮设备
          this.autoHoverDeviceName = null;

          // 短暂延迟后设置新的悬浮设备，创造出连续悬浮之间的过渡间隔
          setTimeout(() => {
            this.currentAutoHoverIndex = (this.currentAutoHoverIndex + 1) % this.uniqueLatheNames.length;

            // 智能选择设备 - 优先显示故障设备
            let priorityIndex = -1;

            // 首先寻找故障设备
            if (this.currentAutoHoverIndex === 0) { // 仅在轮回开始时检查，避免频繁计算
              for (let i = 0; i < this.uniqueLatheNames.length; i++) {
                const latheName = this.uniqueLatheNames[i];
                const summary = this.latheNameSummaries[latheName];
                if (summary && summary.status === '故障') {
                  priorityIndex = i;
                  break;
                }
              }

              // 如果找到故障设备，设置为当前索引
              if (priorityIndex !== -1) {
                this.currentAutoHoverIndex = priorityIndex;
              }
            }

            this.autoHoverDeviceName = this.uniqueLatheNames[this.currentAutoHoverIndex];

            // 智能定位算法 - 确保悬浮框在视口内
            this.$nextTick(() => {
              const deviceItem = document.querySelector(`.device-item.auto-hover-active`);
              const tooltip = document.querySelector(`.device-tooltip.auto-tooltip-active`);

              if (deviceItem && tooltip) {
                deviceItem.getBoundingClientRect();
                const tooltipRect = tooltip.getBoundingClientRect();
                const viewportWidth = window.innerWidth;
// 检查提示框是否溢出左侧或右侧视口
                if (tooltipRect.left < 20) { // 左侧留20px边距
                  // 如果溢出左侧，调整定位
                  tooltip.style.left = '20px';
                  tooltip.style.transform = 'translateX(0) translateY(0) perspective(600px) rotateX(0)';
                  this.tooltipPositionAdjusted = true;
                } else if (tooltipRect.right > viewportWidth - 20) { // 右侧留20px边距
                  // 如果溢出右侧，调整定位
                  tooltip.style.left = 'auto';
                  tooltip.style.right = '20px';
                  tooltip.style.transform = 'translateX(0) translateY(0) perspective(600px) rotateX(0)';
                  this.tooltipPositionAdjusted = true;
                } else if (tooltipRect.top < 20) { // 顶部留20px边距
                  // 如果溢出顶部，调整为底部显示
                  tooltip.style.bottom = 'auto';
                  tooltip.style.top = 'calc(100% + 20px)';
                  // 修改三角形方向
                  tooltip.classList.add('position-bottom');
                  this.tooltipPositionAdjusted = true;
                } else {
                  // 重置调整标记
                  this.tooltipPositionAdjusted = false;
                }

                // 检查是否为故障设备，添加额外信息
                const latheName = this.uniqueLatheNames[this.currentAutoHoverIndex];
                const summary = this.latheNameSummaries[latheName];
                if (summary && summary.status === '故障') {
                  // 为故障设备添加额外信息
                  this.lastHoveredWarningDevice = latheName;
                  if (document.fullscreenElement) { // 仅全屏模式显示额外信息
                    tooltip.setAttribute('data-extra-info', `上次正常时间: ${new Date(summary.lastNormalTime || Date.now() - 3600000).toLocaleTimeString()}`);
                  }
                } else if (this.lastHoveredWarningDevice) {
                  // 清除之前设置的故障设备信息
                  tooltip.removeAttribute('data-extra-info');
                  this.lastHoveredWarningDevice = null;
                }
              }
            });
          }, 200);
        }
,
        stopAutoDeviceHover() {
            if (this.autoHoverTimer) {
                clearInterval(this.autoHoverTimer);
                this.autoHoverTimer = null;
            }
            // 当手动停止时，不立即清除autoHoverDeviceName，让当前悬浮的消失有一个自然的过渡（通过下一次轮播或鼠标移开）
        },
        handleDeviceItemMouseEnter() {
            this.stopAutoDeviceHover();
            this.autoHoverDeviceName = null; // 清除自动悬浮的目标，让CSS hover生效
        },
        handleDeviceItemMouseLeave() {
            // 鼠标移开后，延迟一小段时间再重新启动自动悬浮，避免与快速划过冲突
            // 注释掉自动悬浮重启
            // setTimeout(() => {
            //      // 检查鼠标是否真的移出了所有device-item，避免在项目间移动时频繁启停
            //     const hoveredItem = document.querySelector('.device-item:hover');
            //     if (!hoveredItem) {
            //         this.startAutoDeviceHover();
            //     }
            // }, 300);
        },
        // 跳转到问询页并携带设备ID，直接触发AI分析
        goToInquiry() {
            if (this.currentDevice && this.currentDevice.id) {
                const deviceId = this.currentDevice.id;
                const deviceData = this.deviceAccelerationData[deviceId] || {};

                // 构造完整的 sensorData 对象
                const sensorData = {
                    deviceName: this.currentDevice.latheName || '',
                    sensorId: deviceId,
                    position: this.currentPosition || '',
                    // 假设温度数据在 deviceAccelerationData[deviceId].temperature，如果不是请调整
                    temperature: deviceData.temperature !== undefined ? deviceData.temperature : 0,
                    rmsX: deviceData.rms?.x || [],
                    rmsY: deviceData.rms?.y || [],
                    rmsZ: deviceData.rms?.z || [],
                    peakX: deviceData.peak?.x || [],
                    peakY: deviceData.peak?.y || [],
                    peakZ: deviceData.peak?.z || []
                };

                this.$router.push({
                    path: '/gelly/inquiry',
                    query: {
                        sensorId: deviceId,
                        latheName: this.currentDevice.latheName || '',
                        axis: this.currentPosition || '',
                        // 将 sensorData 对象 JSON.stringify 后再进行 encodeURIComponent 编码
                        data: encodeURIComponent(JSON.stringify(sensorData)),
                        // 新增：标记需要自动触发AI分析
                        autoAnalyze: 'true'
                    }
                });
            }
        },
        buildInquiryDesc(deviceId) {
            const status = this.getDeviceStatus(deviceId);
            const summary = this.latheNameSummaries[this.currentDevice.latheName] || {};
            const time = summary.collectTime ? new Date(summary.collectTime).toLocaleTimeString() : new Date().toLocaleTimeString();

            // 取最近 6 个点（约 1 分钟）RMS X/Y/Z
            const deviceData = this.deviceAccelerationData[deviceId];
            let rmsStr = '';
            if (deviceData && deviceData.rms) {
                const take = 6;
                const lastX = deviceData.rms.x.slice(-take).filter(v=>v).map(v=>v.toFixed(2));
                const lastY = deviceData.rms.y.slice(-take).filter(v=>v).map(v=>v.toFixed(2));
                const lastZ = deviceData.rms.z.slice(-take).filter(v=>v).map(v=>v.toFixed(2));
                rmsStr = `最近${take}点 RMS(X/Y/Z): ${lastX.join(',')} / ${lastY.join(',')} / ${lastZ.join(',')}`;
            }
            return `${status} 状态，采样时间 ${time}。${rmsStr}`;
        },

        // 生成日志消息
        generateLogMessage(record) {
            const deviceName = record.latheName || record.deviceName || '未知设备';
            const status = record.status || '正常';
            const timestamp = new Date(record.createTime || record.timestamp || Date.now());
            const timeStr = timestamp.toLocaleTimeString('zh-CN');

            switch (status) {
                case '故障':
                    return `${timeStr} ${deviceName} 检测到故障信号`;
                case '正常':
                    return `${timeStr} ${deviceName} 运行正常`;
                case '待机':
                    return `${timeStr} ${deviceName} 进入待机状态`;
                case '离线':
                    return `${timeStr} ${deviceName} 设备离线`;
                default:
                    return `${timeStr} ${deviceName} 状态更新`;
            }
        },

        // 获取日志级别
        getLogLevel(status) {
            switch (status) {
                case '故障':
                    return 'error';
                case '正常':
                    return 'success';
                case '待机':
                    return 'warning';
                case '离线':
                    return 'info';
                default:
                    return 'info';
            }
        },

        // 计算设备使用率
        calculateDeviceUsageRates(data) {
            console.log('📊 计算设备使用率...');

            if (!Array.isArray(data) || data.length === 0) {
                // 返回默认使用率数据
                return [85, 82, 88, 84, 86, 83, 87];
            }

            // 按设备分组计算使用率
            const deviceGroups = {};
            data.forEach(item => {
                const deviceId = item.deviceId;
                if (!deviceGroups[deviceId]) {
                    deviceGroups[deviceId] = [];
                }
                deviceGroups[deviceId].push(item);
            });

            // 计算每个设备的使用率
            const usageRates = [];
            Object.keys(deviceGroups).forEach(deviceId => {
                const deviceData = deviceGroups[deviceId];
                const rate = this.calculateSingleDeviceUsageRate(deviceData);
                usageRates.push(rate);
            });

            // 如果没有足够的数据，补充默认值
            while (usageRates.length < 7) {
                usageRates.push(Math.floor(Math.random() * 20) + 80); // 80-100之间的随机值
            }

            return usageRates.slice(0, 7); // 只返回前7个
        },

        // 计算单个设备使用率
        calculateSingleDeviceUsageRate(deviceData) {
            if (!Array.isArray(deviceData) || deviceData.length === 0) {
                return Math.floor(Math.random() * 20) + 80; // 默认80-100
            }

            // 简单的使用率计算逻辑
            // 可以根据实际业务需求调整
            const normalCount = deviceData.filter(item => item.status === '正常').length;
            const totalCount = deviceData.length;

            if (totalCount === 0) return 80;

            const rate = Math.round((normalCount / totalCount) * 100);
            return Math.max(60, Math.min(100, rate)); // 限制在60-100之间
        },

        // 关联设备状态和加速度数据
        associateStatusAndAcceleration() {
            console.log('🔗 关联设备状态和加速度数据...');

            if (!this.deviceStatusData || !this.deviceAccelerationData) {
                console.warn('⚠️ 缺少必要的数据进行关联');
                return;
            }

            // 遍历设备状态数据，与加速度数据关联
            this.deviceStatusData.forEach(statusDevice => {
                const deviceId = statusDevice.deviceId;

                // 如果加速度数据中有对应设备，更新状态信息
                if (this.deviceAccelerationData[deviceId]) {
                    this.deviceAccelerationData[deviceId].status = statusDevice.status;
                    this.deviceAccelerationData[deviceId].lastUpdateTime = statusDevice.updateTime;
                }
            });

            console.log('✅ 设备状态和加速度数据关联完成');
        },

        // 动态更新 latheName 映射
        updateLatheNameMapping(newDeviceData) {
            console.log('🗺️ 动态更新 latheName 映射...');

            // 保存旧的映射关系用于比较
            const oldLatheNameToDeviceMap = { ...this.latheNameToDeviceMap };
            const oldUniqueLatheNames = [...this.uniqueLatheNames];

            // 清空旧的映射，重新构建
            this.latheNameToDeviceMap = {};

            // 重新构建映射关系
            newDeviceData.forEach(device => {
                if (device.latheName && device.deviceId) {
                    if (!this.latheNameToDeviceMap[device.latheName]) {
                        this.latheNameToDeviceMap[device.latheName] = [];
                    }

                    if (!this.latheNameToDeviceMap[device.latheName].includes(device.deviceId)) {
                        this.latheNameToDeviceMap[device.latheName].push(device.deviceId);
                    }
                }
            });

            // 确保所有 DevicesId 中的设备都被映射到某个 latheName
            this.DevicesId.forEach(deviceId => {
                // 检查此设备是否已经在 latheNameToDeviceMap 中
                let found = false;
                for (const latheName in this.latheNameToDeviceMap) {
                    if (this.latheNameToDeviceMap[latheName].includes(deviceId)) {
                        found = true;
                        break;
                    }
                }

                // 如果未在任何 latheName 中找到，添加到默认 latheName
                if (!found) {
                    const defaultName = this.getDeviceName(deviceId);
                    if (!this.latheNameToDeviceMap[defaultName]) {
                        this.latheNameToDeviceMap[defaultName] = [];
                    }
                    this.latheNameToDeviceMap[defaultName].push(deviceId);
                }
            });

            // 更新唯一设备名称列表（保持稳定排序）
            const newUniqueLatheNames = Object.keys(this.latheNameToDeviceMap).sort();

            // 如果是首次初始化或设备数量发生变化，才更新列表
            if (this.uniqueLatheNames.length === 0 || this.uniqueLatheNames.length !== newUniqueLatheNames.length) {
                this.uniqueLatheNames = newUniqueLatheNames;
                console.log('📊 设备列表已更新，新顺序:', this.uniqueLatheNames);
            } else {
                // 否则保持原有顺序，仅添加新设备到末尾
                const existingNames = new Set(this.uniqueLatheNames);
                const newNames = newUniqueLatheNames.filter(name => !existingNames.has(name));
                if (newNames.length > 0) {
                    this.uniqueLatheNames = [...this.uniqueLatheNames, ...newNames.sort()];
                    console.log('📊 新增设备:', newNames);
                }
            }

            // 检查映射关系是否发生变化
            const mappingChanged = this.checkMappingChanges(oldLatheNameToDeviceMap, this.latheNameToDeviceMap);
            const namesChanged = this.checkNamesChanges(oldUniqueLatheNames, this.uniqueLatheNames);

            if (mappingChanged || namesChanged) {
                console.log('📊 设备映射关系发生变化');
                console.log('旧映射:', oldLatheNameToDeviceMap);
                console.log('新映射:', this.latheNameToDeviceMap);

                // 触发映射变化事件
                this.onMappingChanged(oldLatheNameToDeviceMap, this.latheNameToDeviceMap);
            }

            console.log('✅ latheName 映射更新完成，设备数量:', this.uniqueLatheNames.length);
        },

        // 检查映射关系是否发生变化
        checkMappingChanges(oldMapping, newMapping) {
            const oldKeys = Object.keys(oldMapping);
            const newKeys = Object.keys(newMapping);

            // 检查键的数量是否变化
            if (oldKeys.length !== newKeys.length) {
                return true;
            }

            // 检查每个键及其对应的设备列表是否变化
            for (const key of newKeys) {
                if (!oldMapping[key]) {
                    return true; // 新增的 latheName
                }

                const oldDevices = oldMapping[key].sort();
                const newDevices = newMapping[key].sort();

                if (oldDevices.length !== newDevices.length) {
                    return true;
                }

                for (let i = 0; i < oldDevices.length; i++) {
                    if (oldDevices[i] !== newDevices[i]) {
                        return true;
                    }
                }
            }

            // 检查是否有删除的 latheName
            for (const key of oldKeys) {
                if (!newMapping[key]) {
                    return true; // 删除的 latheName
                }
            }

            return false;
        },

        // 检查设备名称列表是否发生变化
        checkNamesChanges(oldNames, newNames) {
            if (oldNames.length !== newNames.length) {
                return true;
            }

            const sortedOldNames = [...oldNames].sort();
            const sortedNewNames = [...newNames].sort();

            for (let i = 0; i < sortedOldNames.length; i++) {
                if (sortedOldNames[i] !== sortedNewNames[i]) {
                    return true;
                }
            }

            return false;
        },

        // 映射关系变化时的处理
        onMappingChanged(oldMapping, newMapping) {
            console.log('🔄 处理映射关系变化...');

            // 可以在这里添加映射变化后的处理逻辑
            // 例如：更新当前选中的设备、刷新图表等

            // 如果当前选中的设备的 latheName 发生了变化，需要更新
            if (this.currentDevice && this.currentDevice.latheName) {
                const currentLatheName = this.currentDevice.latheName;
                if (!newMapping[currentLatheName] && oldMapping[currentLatheName]) {
                    console.log('⚠️ 当前选中设备的 latheName 已不存在，需要重新选择');
                    // 选择第一个可用的设备
                    if (this.uniqueLatheNames.length > 0) {
                        this.selectLatheNameDevice(this.uniqueLatheNames[0]);
                    }
                }
            }
        },

        // 更新设备映射关系（保留原有方法作为兼容）
        updateDeviceMapping() {
            console.log('🗺️ 更新设备映射关系（兼容方法）...');
            this.updateLatheNameMapping(this.deviceStatusData);
        },

        // 生成综合监控日志
        generateComprehensiveMonitorLogs() {
            console.log('📝 生成综合监控日志...');

            const comprehensiveLogs = [];

            // 基于设备状态生成日志
            if (this.deviceStatusData) {
                this.deviceStatusData.forEach(device => {
                    if (device.status === '故障') {
                        comprehensiveLogs.push({
                            id: `status_${device.deviceId}_${Date.now()}`,
                            deviceName: device.latheName || device.deviceName || '未知设备',
                            deviceId: device.deviceId,
                            status: device.status,
                            message: this.generateLogMessage(device),
                            timestamp: device.updateTime || new Date().toISOString(),
                            level: 'error',
                            type: 'status'
                        });
                    }
                });
            }

            // 合并现有监控日志
            if (this.monitorLogs && this.monitorLogs.length > 0) {
                comprehensiveLogs.push(...this.monitorLogs);
            }

            // 按时间排序，最新的在前
            comprehensiveLogs.sort((a, b) => {
                const timeA = new Date(a.timestamp).getTime();
                const timeB = new Date(b.timestamp).getTime();
                return timeB - timeA;
            });

            // 更新监控日志，只保留最近的记录
            this.monitorLogs = comprehensiveLogs.slice(0, 8);

            console.log('✅ 综合监控日志生成完成，日志数量:', this.monitorLogs.length);
        },

        // 基于中间设备展示区域的数据生成监测记录
        generateDetectionRecordsFromStatus(statusData) {
            console.log('🔄 基于中间设备展示区域数据生成监测记录...');

            const records = [];
            const now = Date.now();

            // 优先使用 latheNameSummaries（中间设备展示区域的数据）
            if (this.latheNameSummaries && Object.keys(this.latheNameSummaries).length > 0) {
                console.log('📊 使用设备汇总数据生成监测记录');

                Object.entries(this.latheNameSummaries).forEach(([latheName, summary], index) => {
                    const normalizedStatus = this.normalizeDeviceStatus(summary.status);
                    const recordTime = summary.collectTime || new Date(now - index * 30000).toISOString(); // 每30秒间隔

                    // 获取设备ID
                    const deviceIds = this.latheNameToDeviceMap[latheName] || [];
                    const deviceId = deviceIds[0] || `device_${index}`;

                    const record = {
                        id: `lathe_${latheName}_${now}`,
                        deviceId: deviceId,
                        latheName: latheName,
                        deviceName: latheName,
                        status: normalizedStatus,
                        createTime: recordTime,
                        timestamp: recordTime,
                        message: this.generateStatusMessage({
                            latheName: latheName,
                            status: normalizedStatus
                        }),
                        type: 'device_monitor',
                        source: 'lathe_summary',
                        collectTime: summary.collectTime
                    };

                    records.push(record);
                });

                console.log('✅ 基于设备汇总生成记录:', records.length, '条');
            }

            // 如果设备汇总数据不足，补充原始设备状态数据
            if (records.length < 5 && Array.isArray(statusData)) {
                console.log('📊 补充原始设备状态数据');

                const existingDevices = new Set(records.map(r => r.latheName));

                statusData.forEach((device, index) => {
                    const deviceKey = device.latheName || device.deviceName || device.deviceId;

                    if (!existingDevices.has(deviceKey) && records.length < 15) {
                        const normalizedStatus = this.normalizeDeviceStatus(device.status);
                        const recordTime = device.updateTime || new Date(now - (records.length + index) * 30000).toISOString();

                        const record = {
                            id: `device_${device.deviceId}_${now}`,
                            deviceId: device.deviceId,
                            latheName: device.latheName || device.deviceName || '未知设备',
                            deviceName: device.latheName || device.deviceName || '未知设备',
                            status: normalizedStatus,
                            createTime: recordTime,
                            timestamp: recordTime,
                            message: this.generateStatusMessage({
                                ...device,
                                status: normalizedStatus
                            }),
                            type: 'device_status',
                            source: 'device_data'
                        };

                        records.push(record);
                        existingDevices.add(deviceKey);
                    }
                });

                console.log('✅ 补充设备状态数据:', records.length, '条');
            }

            // 按状态优先级排序：故障 > 待机 > 正常 > 离线，然后按时间排序
            records.sort((a, b) => {
                const statusPriority = { '故障': 4, '待机': 3, '正常': 2, '离线': 1 };
                const priorityA = statusPriority[a.status] || 0;
                const priorityB = statusPriority[b.status] || 0;

                if (priorityA !== priorityB) {
                    return priorityB - priorityA; // 优先级高的在前
                }

                // 同优先级按时间排序
                const timeA = new Date(a.createTime).getTime();
                const timeB = new Date(b.createTime).getTime();
                return timeB - timeA;
            });

            console.log('✅ 监测记录生成完成，记录数量:', records.length);

            // 打印状态分布
            const statusCount = {};
            records.forEach(record => {
                statusCount[record.status] = (statusCount[record.status] || 0) + 1;
            });
            console.log('📊 状态分布:', statusCount);

            return records;
        },

        // 生成默认检测记录
        generateDefaultDetectionRecords() {
            console.log('🔄 生成默认检测记录...');

            const defaultRecords = [];
            const now = Date.now();

            // 基于当前设备列表生成，如果没有则使用默认设备
            const deviceList = this.uniqueLatheNames && this.uniqueLatheNames.length > 0
                ? this.uniqueLatheNames
                : ['磨床001', '磨床002', '磨床003', '磨床004', '磨床005'];

            // 为每个设备生成检测记录
            deviceList.forEach((deviceName, deviceIndex) => {
                // 每个设备生成2-3条历史记录
                const recordCount = Math.floor(Math.random() * 2) + 2; // 2-3条

                for (let i = 0; i < recordCount; i++) {
                    const timeOffset = (deviceIndex * recordCount + i) * 600000; // 每10分钟一条
                    const timestamp = new Date(now - timeOffset).toISOString();

                    // 生成合理的状态分布
                    let status;
                    if (i === 0) {
                        // 最新记录，80%概率正常
                        status = Math.random() < 0.8 ? '正常' : (Math.random() < 0.5 ? '待机' : '故障');
                    } else {
                        // 历史记录，更多样化
                        const statusOptions = ['正常', '待机', '离线'];
                        if (Math.random() < 0.1) statusOptions.push('故障'); // 10%概率故障
                        status = statusOptions[Math.floor(Math.random() * statusOptions.length)];
                    }

                    const deviceId = this.latheNameToDeviceMap && this.latheNameToDeviceMap[deviceName]
                        ? this.latheNameToDeviceMap[deviceName][0]
                        : `30096${String(deviceIndex + 420).padStart(3, '0')}`;

                    defaultRecords.push({
                        id: `default_${now}_${deviceIndex}_${i}`,
                        deviceId: deviceId,
                        latheName: deviceName,
                        deviceName: deviceName,
                        status: status,
                        createTime: timestamp,
                        timestamp: timestamp,
                        message: this.generateStatusMessage({
                            latheName: deviceName,
                            status: status
                        }),
                        type: 'default',
                        source: 'generated_default'
                    });
                }
            });

            // 按时间排序，最新的在前
            defaultRecords.sort((a, b) => {
                const timeA = new Date(a.createTime).getTime();
                const timeB = new Date(b.createTime).getTime();
                return timeB - timeA;
            });

            console.log('✅ 生成默认检测记录完成，记录数量:', defaultRecords.length);
            return defaultRecords.slice(0, 15); // 返回最近15条
        },

        // 标准化设备状态
        normalizeDeviceStatus(status) {
            if (!status || typeof status !== 'string') {
                return '离线';
            }

            const normalizedStatus = status.trim();

            // 标准化状态名称
            switch (normalizedStatus) {
                case '在线':
                case '正常':
                case 'online':
                case 'normal':
                    return '正常';
                case '故障':
                case '异常':
                case 'error':
                case 'fault':
                    return '故障';
                case '待机':
                case '空闲':
                case 'idle':
                case 'standby':
                    return '待机';
                case '离线':
                case '断开':
                case 'offline':
                case 'disconnected':
                default:
                    return '离线';
            }
        },

        // 生成状态消息
        generateStatusMessage(device) {
            const deviceName = device.latheName || device.deviceName || '未知设备';
            const status = this.normalizeDeviceStatus(device.status);
            const time = new Date().toLocaleTimeString('zh-CN');

            switch (status) {
                case '正常':
                    return `${time} ${deviceName} 运行正常`;
                case '故障':
                    return `${time} ${deviceName} 检测到故障信号`;
                case '待机':
                    return `${time} ${deviceName} 进入待机状态`;
                case '离线':
                default:
                    return `${time} ${deviceName} 设备离线`;
            }
        },

        // 格式化日志时间
        formatLogTime(timestamp) {
            if (!timestamp) return '';

            const date = new Date(timestamp);
            const now = new Date();
            const diffMs = now.getTime() - date.getTime();
            const diffMinutes = Math.floor(diffMs / (1000 * 60));
            const diffHours = Math.floor(diffMs / (1000 * 60 * 60));

            if (diffMinutes < 1) {
                return '刚刚';
            } else if (diffMinutes < 60) {
                return `${diffMinutes}分钟前`;
            } else if (diffHours < 24) {
                return `${diffHours}小时前`;
            } else {
                return date.toLocaleDateString('zh-CN') + ' ' + date.toLocaleTimeString('zh-CN', {
                    hour: '2-digit',
                    minute: '2-digit'
                });
            }
        },

        // 从监测记录跳转问询
        inquiryFromLog(log) {
            if (!log || !log.deviceName) return;
            let deviceId = null;
            // 优先从 latheNameToDeviceMap 获取
            if (this.latheNameToDeviceMap[log.deviceName] && this.latheNameToDeviceMap[log.deviceName].length > 0) {
                deviceId = this.latheNameToDeviceMap[log.deviceName][0];
            } else {
                // 退而求其次，遍历 deviceStatusData
                const dev = this.deviceStatusData.find(d => d.latheName === log.deviceName);
                if (dev) deviceId = dev.deviceId;
            }
            if (deviceId) {
                const query = {
                    sensorId: deviceId,
                    latheName: log.deviceName || '',
                };
                if (log.axis) query.axis = log.axis; // 若后续日志带 axis
                query.desc = this.buildInquiryDesc(deviceId);
                this.$router.push({ path: '/gelly/inquiry', query });
            } else {
                this.$message.warning('无法定位该设备编号');
            }
        },

        // 从检测记录卡片跳转问询
        inquiryFromDevice(deviceInfo) {
            if (!deviceInfo || !deviceInfo.deviceName) return;

            console.log('🔍 从检测记录卡片问询设备:', deviceInfo);

            let deviceId = null;
            // 优先从 latheNameToDeviceMap 获取
            if (this.latheNameToDeviceMap[deviceInfo.deviceName] && this.latheNameToDeviceMap[deviceInfo.deviceName].length > 0) {
                deviceId = this.latheNameToDeviceMap[deviceInfo.deviceName][0];
            } else {
                // 退而求其次，遍历 deviceStatusData
                const dev = this.deviceStatusData.find(d => d.latheName === deviceInfo.deviceName);
                if (dev) deviceId = dev.deviceId;
            }

            if (deviceId) {
                const query = {
                    sensorId: deviceId,
                    latheName: deviceInfo.deviceName || '',
                };
                // 添加设备状态信息到查询参数
                if (deviceInfo.status) query.status = deviceInfo.status;
                if (deviceInfo.collectTime) query.collectTime = deviceInfo.collectTime;

                query.desc = this.buildInquiryDesc(deviceId);

                console.log(`🚀 跳转到设备 ${deviceInfo.deviceName} (ID: ${deviceId}) 的问询页面`);
                this.$router.push({ path: '/gelly/inquiry', query });
            } else {
                this.$message.warning('无法定位该设备编号');
            }
        },

        // ==================== WebSocket和滑动窗口管理器相关方法 ====================

        /**
         * 超强性能优化的WebSocket初始化
         */
        async initializeWebSocketWithPerformanceOptimization() {
            console.log('🚀 启动超强性能优化的WebSocket...');

            try {
                // 1. 初始化WebSocket服务（禁用心跳）
                this.webSocketService = new DeviceWebSocketService();

                // 2. 临时禁用心跳机制，避免周期性卡顿
                if (this.webSocketService) {
                    this.webSocketService.heartbeatInterval = 300000; // 5分钟心跳，减少频率
                    console.log('📊 WebSocket心跳间隔设置为5分钟');
                }

                // 3. 设置超强节流的事件监听器
                this.setupPerformanceOptimizedWebSocketListeners();

                // 4. 连接WebSocket
                await this.connectWebSocket();

                // 5. 初始化数据管理器
                await this.initializeChartDataManager();

                console.log('✅ 超强性能优化WebSocket初始化完成');
            } catch (error) {
                console.error('❌ 超强性能优化WebSocket初始化失败:', error);
                throw error;
            }
        },

        /**
         * 设置超强节流的WebSocket事件监听器
         */
        setupPerformanceOptimizedWebSocketListeners() {
            if (!this.webSocketService) return;

            // 连接成功事件
            this.webSocketService.on('connected', () => {
                console.log('✅ WebSocket连接成功');
                this.isWebSocketConnected = true;
                this.webSocketReconnectAttempts = 0;

                // 订阅当前设备的加速度数据
                if (this.currentDevice && this.currentDevice.id) {
                    this.subscribeCurrentDeviceData();
                }
            });

            // 超强节流的设备信息更新
            this.webSocketService.on('deviceInfoUpdate', (data) => {
                // 最强节流：每5秒最多处理一次
                const now = Date.now();
                const lastProcess = this._lastWebSocketProcess || 0;
                if (now - lastProcess < 5000) {
                    console.log('📊 WebSocket数据处理被节流跳过');
                    return;
                }
                this._lastWebSocketProcess = now;

                console.log('🔔 WebSocket事件监听器收到设备信息更新（节流后）:', data);
                this.handleWebSocketDeviceInfoUpdateUltraThrottled(data);
            });

            // 错误处理
            this.webSocketService.on('error', (error) => {
                console.error('WebSocket错误:', error);
                this.handleWebSocketError(error);
            });
        },

        /**
         * 初始化WebSocket和数据管理器
         */
        async initializeWebSocketAndDataManager() {
            try {
                console.log('🚀 开始初始化WebSocket和数据管理器...');

                // 初始化新的图表数据管理器
                this.chartDataManager = new ChartDataManager({
                    displayWindowSize: 600, // 显示600个数据点
                    historicalDataRetention: 24 * 60 * 60 * 1000, // 保留24小时历史数据
                    realtimeDataRetention: 60 * 60 * 1000, // 保留1小时实时数据
                    updateThrottle: 100 // 100ms更新节流，平衡响应性和性能
                });

                // 设置数据更新回调
                this.chartDataManager.setUpdateCallback((deviceIds) => {
                    console.log('📊 数据管理器触发更新:', deviceIds);
                    // 通知图表组件更新
                    if (this.$bus) {
                        this.$bus.$emit('chartDataUpdate', deviceIds);
                    }
                });

                console.log('✅ 图表数据管理器初始化完成');

                // 初始化WebSocket服务
                this.webSocketService = new DeviceWebSocketService();

                // 设置WebSocket事件监听器
                this.setupWebSocketEventListeners();

                // 连接WebSocket
                await this.connectWebSocket();

                console.log('✅ WebSocket和数据管理器初始化完成');
            } catch (error) {
                console.error('❌ WebSocket和数据管理器初始化失败:', error);
                // 如果WebSocket初始化失败，回退到HTTP轮询模式
                this.fallbackToPollingMode();
            }
        },

        /**
         * 设置WebSocket事件监听器
         */
        setupWebSocketEventListeners() {
            if (!this.webSocketService) return;

            // 监听连接成功事件
            this.webSocketService.on('connected', () => {
                console.log('✅ WebSocket连接成功');
                this.isWebSocketConnected = true;
                this.webSocketReconnectAttempts = 0;

                // 订阅当前设备的加速度数据
                if (this.currentDevice && this.currentDevice.id) {
                    this.subscribeCurrentDeviceData();
                }
            });

            // 监听连接断开事件
            this.webSocketService.on('disconnected', () => {
                console.log('⚠️ WebSocket连接断开');
                this.isWebSocketConnected = false;
            });

            // 监听加速度数据更新
            this.webSocketService.on('accelerationDataUpdate', (data) => {
                console.log('🔔 WebSocket事件监听器收到加速度数据:', data);
                this.handleWebSocketAccelerationData(data);
            });

            // 监听设备信息更新（包含加速度数据）
            this.webSocketService.on('deviceInfoUpdate', (data) => {
                console.log('🔔 WebSocket事件监听器收到设备信息更新:', data);
                this.handleWebSocketDeviceInfoUpdate(data);
            });

            // 监听设备状态更新
            this.webSocketService.on('deviceStatusUpdate', (data) => {
                console.log('🔔 WebSocket事件监听器收到设备状态更新:', data);
                this.handleWebSocketDeviceStatusUpdate(data);
            });

            // 监听错误事件
            this.webSocketService.on('error', (error) => {
                console.error('WebSocket错误:', error);
                this.handleWebSocketError(error);
            });
        },

        /**
         * 连接WebSocket
         */
        async connectWebSocket() {
            if (!this.webSocketService) return;

            try {
                // 使用配置的WebSocket地址
                const wsUrl = process.env.VUE_APP_WS_URL || 'ws://localhost:8081/ws/device-monitor';
                await this.webSocketService.connect(wsUrl);
            } catch (error) {
                console.error('WebSocket连接失败:', error);
                throw error;
            }
        },

        /**
         * 订阅当前设备的数据
         */
        subscribeCurrentDeviceData() {
            if (!this.webSocketService || !this.currentDevice) return;

            console.log(`📡 订阅设备数据: ${this.currentDevice.id} (${this.currentDevice.latheName})`);

            // 订阅加速度数据
            this.webSocketService.subscribeAccelerationData(
                this.currentDevice.id,
                this.currentDevice.latheName
            );
        },

        /**
         * 取消订阅设备数据
         */
        unsubscribeDeviceData(deviceId) {
            if (!this.webSocketService || !deviceId) return;

            console.log(`📡 取消订阅设备数据: ${deviceId}`);
            this.webSocketService.unsubscribeAccelerationData(deviceId);
        },

        /**
         * 处理WebSocket加速度数据（使用新的数据管理器）
         */
        handleWebSocketAccelerationData(data) {
            if (!data || !data.deviceId) return;

            // 仅为当前设备输出详细日志，减少控制台输出开销
            if (data.deviceId === this.currentDevice.id) {
                console.log('📊 收到当前设备WebSocket数据:', data.deviceId);
            }

            // 使用新的数据管理器处理实时数据
            if (this.chartDataManager) {
                this.chartDataManager.addRealtimeData(data.deviceId, data);
            }

            // 极简节流：仅对当前设备进行最小化节流
            if (data.deviceId === this.currentDevice.id) {
                const now = Date.now();
                const lastUpdate = this._currentDeviceLastUpdate || 0;

                // 当前设备使用50ms节流，保证波形图流畅
                if (now - lastUpdate >= 50) {
                    this._currentDeviceLastUpdate = now;

                    this.updateDeviceAccelerationDataFromWebSocket(data);

                    // 立即触发UI更新
                    if (this.$bus) {
                        this.$bus.$emit('accelerationDataUpdate', {
                            deviceId: data.deviceId,
                            data: data,
                            timestamp: data.timestamp || Date.now()
                        });
                    }
                }
            } else {
                // 非当前设备使用更长节流，减少处理开销
                const now = Date.now();
                const deviceKey = `device_${data.deviceId}`;
                const lastUpdate = this._otherDevicesUpdateTimes?.[deviceKey] || 0;

                if (now - lastUpdate >= 500) { // 500ms节流
                    if (!this._otherDevicesUpdateTimes) {
                        this._otherDevicesUpdateTimes = {};
                    }
                    this._otherDevicesUpdateTimes[deviceKey] = now;

                    // 仅更新数据，不触发UI
                    this.updateDeviceAccelerationDataFromWebSocket(data);
                }
            }
        },

        /**
         * 直接从WebSocket数据更新设备加速度数据（备用方案）
         */
        updateDeviceAccelerationDataFromWebSocket(data) {
            if (!data || !data.deviceId) return;

            const deviceId = data.deviceId;

            // 确保设备数据结构存在（参考index_before.vue实现）
            if (!this.deviceAccelerationData[deviceId]) {
                // 创建10秒间隔的时间点（60个点，覆盖10分钟）
                const timePoints = Array(60).fill('').map((_, index) => {
                    const time = new Date(Date.now() - (59 - index) * 10000); // 10秒 = 10000毫秒
                    return time.toLocaleTimeString('zh-CN', {
                        hour: '2-digit',
                        minute: '2-digit',
                        second: '2-digit' // 添加秒显示
                    });
                });

                // 初始化设备数据结构
                this.deviceAccelerationData[deviceId] = {
                    latheName: data.latheName || null,
                    putPlace: data.putPlace || '',
                    deviceLocation: data.deviceLocation || '',
                    bindLocation: data.bindLocation || '',
                    rms: {
                        x: Array(60).fill(null),
                        y: Array(60).fill(null),
                        z: Array(60).fill(null)
                    },
                    peak: {
                        x: Array(60).fill(null),
                        y: Array(60).fill(null),
                        z: Array(60).fill(null)
                    },
                    timeData: timePoints,
                    lastUpdateTime: Date.now() // 记录最后更新时间
                };
            }

            // 更新设备的加速度数据（参考index_before.vue实现）
            const deviceAccData = this.deviceAccelerationData[deviceId];

            // 更新设备名称，但不覆盖安装位置（如果当前设备已选择特定位置）
            if (data.latheName) {
                deviceAccData.latheName = data.latheName;
            }
            if (data.putPlace) {
                deviceAccData.putPlace = data.putPlace;
            }
            if (data.deviceLocation) {
                deviceAccData.deviceLocation = data.deviceLocation;
            }
            if (data.bindLocation) {
                deviceAccData.bindLocation = data.bindLocation;
            }

            const now = Date.now();
            const timeSinceLastUpdate = now - (deviceAccData.lastUpdateTime || 0);

            // 检查是否需要添加新数据点（5秒间隔）
            if (timeSinceLastUpdate >= 5000 || !deviceAccData.lastUpdateTime) {
                console.log(`📈 设备 ${deviceId} 添加新数据点，时间间隔: ${timeSinceLastUpdate}ms`);

                // 数据左移，添加新数据点（参考index_before.vue的滑动窗口实现）
                for (let i = 0; i < 59; i++) {
                    deviceAccData.timeData[i] = deviceAccData.timeData[i + 1];
                    deviceAccData.rms.x[i] = deviceAccData.rms.x[i + 1];
                    deviceAccData.rms.y[i] = deviceAccData.rms.y[i + 1];
                    deviceAccData.rms.z[i] = deviceAccData.rms.z[i + 1];
                    deviceAccData.peak.x[i] = deviceAccData.peak.x[i + 1];
                    deviceAccData.peak.y[i] = deviceAccData.peak.y[i + 1];
                    deviceAccData.peak.z[i] = deviceAccData.peak.z[i + 1];
                }

                // 添加新数据到最后一位
                deviceAccData.timeData[59] = new Date().toLocaleTimeString('zh-CN', {
                    hour: '2-digit',
                    minute: '2-digit',
                    second: '2-digit'
                });
                deviceAccData.rms.x[59] = data.xrms || 0;
                deviceAccData.rms.y[59] = data.yrms || 0;
                deviceAccData.rms.z[59] = data.zrms || 0;
                deviceAccData.peak.x[59] = data.xpeak || 0;
                deviceAccData.peak.y[59] = data.ypeak || 0;
                deviceAccData.peak.z[59] = data.zpeak || 0;

                deviceAccData.lastUpdateTime = now;
            } else {
                // 仅更新最新点的值（不添加新点）
                console.log(`📊 设备 ${deviceId} 更新最新数据点值`);
                deviceAccData.rms.x[59] = data.xrms || 0;
                deviceAccData.rms.y[59] = data.yrms || 0;
                deviceAccData.rms.z[59] = data.zrms || 0;
                deviceAccData.peak.x[59] = data.xpeak || 0;
                deviceAccData.peak.y[59] = data.ypeak || 0;
                deviceAccData.peak.z[59] = data.zpeak || 0;
            }

            console.log(`📈 设备 ${deviceId} 加速度数据已更新`, {
                time: deviceAccData.timeData[59],
                rms: { x: deviceAccData.rms.x[59], y: deviceAccData.rms.y[59], z: deviceAccData.rms.z[59] },
                peak: { x: deviceAccData.peak.x[59], y: deviceAccData.peak.y[59], z: deviceAccData.peak.z[59] }
            });

            // 优化：避免强制响应式更新和对象拷贝，减少性能开销
            // this.$set(this.deviceAccelerationData, deviceId, { ...deviceAccData });
        },

        /**
         * 获取加速度图表配置（参考index_before.vue实现）
         */
        getAccelerationChartOption() {
            const deviceId = this.currentDevice.id;
            let deviceData = this.deviceAccelerationData[deviceId];

            // 如果没有数据，确保创建一个空的结构供图表使用，以保证formatter能运行
            if (!deviceData) {
                console.warn(`[getAccelerationChartOption] No deviceData for ${deviceId}, creating placeholder.`);
                const placeholderTimeData = Array(60).fill(null);
                // Create a minimal placeholder structure if it's truly missing
                // This helps the formatter logic to still execute with [0] and [59]
                this.deviceAccelerationData[deviceId] = {
                    latheName: this.currentDevice.latheName || '未知设备',
                    putPlace: this.currentDevice.putPlace || '',
                    deviceLocation: '',
                    bindLocation: '',
                    rms: { x: Array(60).fill(null), y: Array(60).fill(null), z: Array(60).fill(null) },
                    peak: { x: Array(60).fill(null), y: Array(60).fill(null), z: Array(60).fill(null) },
                    timeData: placeholderTimeData,
                    lastUpdateTime: Date.now()
                };
                deviceData = this.deviceAccelerationData[deviceId];
            }

            // 如果没有数据，返回空图表配置
            if (!deviceData) {
                return {
                    xAxis: {
                        type: 'category',
                        data: []
                    },
                    yAxis: {
                        type: 'value',
                        name: this.accelerationType === 'rms' ? 'RMS(m/s²)' : 'PEAK(m/s²)',
                        splitLine: {
                            lineStyle: {
                                color: 'rgba(255,255,255,0.3)',
                                type: 'dashed'
                            }
                        }
                    },
                    series: [
                        {
                            name: 'X轴',
                            type: 'line',
                            data: [],
                            lineStyle: { color: 'red', width: 2 }
                        },
                        {
                            name: 'Y轴',
                            type: 'line',
                            data: [],
                            lineStyle: { color: 'yellow', width: 2 }
                        },
                        {
                            name: 'Z轴',
                            type: 'line',
                            data: [],
                            lineStyle: { color: 'green', width: 2 }
                        }
                    ],
                    grid: {
                        top: 40,
                        left: 50,
                        right: 30,
                        bottom: 70
                    },
                    legend: {
                        show: true,
                        top: 10,
                        right: 10,
                        textStyle: {
                            color: 'rgba(255,255,255,0.8)',
                            fontSize: 12
                        },
                        data: ['X轴', 'Y轴', 'Z轴']
                    }
                };
            }

            const currentData = this.accelerationType === 'rms' ?
                deviceData.rms : deviceData.peak;

            // 计算数据的最大值和最小值，用于自适应Y轴
            let dataMax = 0;
            let dataMin = Number.MAX_VALUE;

            // 遍历所有数据点找出最大值和最小值
            ['x', 'y', 'z'].forEach(axis => {
                // 筛选掉0值，这些通常是初始化或无效数据
                const validData = currentData[axis].filter(val => val > 0);
                if (validData.length > 0) {
                    const maxVal = Math.max(...validData);
                    const minVal = Math.min(...validData);

                    if (maxVal > dataMax) {
                        dataMax = maxVal;
                    }

                    if (minVal < dataMin) {
                        dataMin = minVal;
                    }
                }
            });

            // 如果最小值仍然是初始值，或者数据都是0，则设置为0
            if (dataMin === Number.MAX_VALUE || dataMax === 0) {
                dataMin = 0;
                dataMax = 1; // 避免空图表
            }

            // 智能调整Y轴范围
            const yAxisMin = 0;
            let yAxisMax = dataMax > 0 ? dataMax * 1.2 : 10;
            if (yAxisMax === 0 && dataMin === 0) yAxisMax = 10;
            if (yAxisMax <= yAxisMin) yAxisMax = yAxisMin + 10;

            // 设置适合的背景色和线条颜色，与参考图片类似
            const colors = {
                x: {
                    line: '#4a7eff', // 蓝色
                    area: 'rgba(74, 126, 255, 0.15)' // 淡蓝色透明
                },
                y: {
                    line: '#59d666', // 绿色
                    area: 'rgba(89, 214, 102, 0.15)' // 淡绿色透明
                },
                z: {
                    line: '#ff5a5a', // 红色
                    area: 'rgba(255, 90, 90, 0.15)' // 淡红色透明
                }
            };

            return {
                backgroundColor: 'rgba(250, 250, 250, 0.05)',
                tooltip: {
                    trigger: 'axis',
                    formatter: function(params) {
                        let result = params[0].axisValue + '<br/>';

                        params.forEach(param => {
                            const color = param.color;
                            const seriesName = param.seriesName;
                            const value = param.value;

                            result += `<span style="display:inline-block;margin-right:5px;border-radius:50%;width:10px;height:10px;background-color:${color};"></span>`;
                            result += `${seriesName}: ${value.toFixed(3)} m/s²<br/>`;
                        });

                        return result;
                    },
                    axisPointer: {
                        type: 'line',
                        lineStyle: {
                            color: 'rgba(255,255,255,0.5)',
                            width: 1
                        }
                    },
                    backgroundColor: 'rgba(50,50,50,0.9)',
                    borderColor: 'rgba(255,255,255,0.3)',
                    textStyle: {
                        color: '#fff'
                    }
                },
                xAxis: {
                    type: 'category',
                    data: deviceData.timeData,
                    axisLabel: {
                        color: 'rgba(255,255,255,0.7)',
                        fontSize: 10,
                        rotate: 0,
                        interval: (index, value) => {
                            // 显示20个时间标签，每3个点显示一个
                            if (index === 0) return true; // 总是显示第一个
                            if (index === deviceData.timeData.length - 1) return false; // 不显示最后一个避免重叠
                            return index % 3 === 0; // 每3个点显示一个标签
                        }
                    },
                    axisLine: {
                        lineStyle: {
                            color: 'rgba(255,255,255,0.3)'
                        }
                    },
                    axisTick: {
                        show: true,
                        lineStyle: {
                            color: 'rgba(255,255,255,0.3)'
                        },
                        interval: (index, value) => {
                            // 与标签显示保持一致
                            if (index === 0) return true;
                            if (index === deviceData.timeData.length - 1) return false;
                            return index % 3 === 0;
                        }
                    },
                    name: '',
                    nameLocation: 'end',
                    nameGap: 15,
                    nameTextStyle: {
                        color: 'rgba(255,255,255,0.7)',
                        fontSize: 10,
                        padding: [0, 0, 0, 0]
                    }
                },
                yAxis: {
                    type: 'value',
                    name: this.accelerationType === 'rms' ? 'RMS(m/s²)' : 'PEAK(m/s²)',
                    min: yAxisMin,
                    max: yAxisMax,
                    splitLine: {
                        lineStyle: {
                            color: 'rgba(255,255,255,0.3)',
                            type: 'dashed'
                        }
                    },
                    axisLabel: {
                        formatter: function(value) {
                            return value.toFixed(2);
                        },
                        color: 'rgba(255,255,255,0.7)'
                    },
                    nameTextStyle: {
                        color: 'rgba(255,255,255,0.7)'
                    }
                },
                series: [
                    {
                        name: 'X轴',
                        type: 'line',
                        showSymbol: false,
                        smooth: true,
                        lineStyle: {
                            color: colors.x.line,
                            width: 2
                        },
                        itemStyle: {
                            color: colors.x.line,
                            borderWidth: 2,
                            borderColor: '#fff'
                        },
                        emphasis: {
                            itemStyle: {
                                color: '#fff',
                                borderColor: colors.x.line,
                                borderWidth: 3,
                                shadowColor: 'rgba(74, 126, 255, 0.8)',
                                shadowBlur: 5
                            }
                        },
                        data: currentData.x,
                        z: 1,
                        areaStyle: {
                            color: colors.x.area,
                            origin: 'start'
                        }
                    },
                    {
                        name: 'Y轴',
                        type: 'line',
                        showSymbol: false,
                        smooth: true,
                        lineStyle: {
                            color: colors.y.line,
                            width: 2
                        },
                        itemStyle: {
                            color: colors.y.line,
                            borderWidth: 2,
                            borderColor: '#fff'
                        },
                        emphasis: {
                            itemStyle: {
                                color: '#fff',
                                borderColor: colors.y.line,
                                borderWidth: 3,
                                shadowColor: 'rgba(89, 214, 102, 0.8)',
                                shadowBlur: 5
                            }
                        },
                        data: currentData.y,
                        z: 2,
                        areaStyle: {
                            color: colors.y.area,
                            origin: 'start'
                        }
                    },
                    {
                        name: 'Z轴',
                        type: 'line',
                        showSymbol: false,
                        smooth: true,
                        lineStyle: {
                            color: colors.z.line,
                            width: 2
                        },
                        itemStyle: {
                            color: colors.z.line,
                            borderWidth: 2,
                            borderColor: '#fff'
                        },
                        emphasis: {
                            itemStyle: {
                                color: '#fff',
                                borderColor: colors.z.line,
                                borderWidth: 3,
                                shadowColor: 'rgba(255, 90, 90, 0.8)',
                                shadowBlur: 5
                            }
                        },
                        data: currentData.z,
                        z: 3,
                        areaStyle: {
                            color: colors.z.area,
                            origin: 'start'
                        }
                    }
                ],
                grid: {
                    top: 40,
                    left: 50,
                    right: 30,
                    bottom: 70
                },
                legend: {
                    show: true,
                    top: 10,
                    right: 10,
                    textStyle: {
                        color: 'rgba(255,255,255,0.8)',
                        fontSize: 12
                    },
                    data: ['X轴', 'Y轴', 'Z轴']
                }
            };
        },

        /**
         * 处理滑动窗口数据更新
         */
        handleWindowDataUpdate(data) {
            if (!data || !data.deviceId) return;

            console.log('📈 滑动窗口数据更新:', data.deviceId);

            // 更新设备加速度数据存储
            if (data.data) {
                this.deviceAccelerationData[data.deviceId] = {
                    ...this.deviceAccelerationData[data.deviceId],
                    latheName: data.latheName,
                    rms: data.data.rms,
                    peak: data.data.peak,
                    timeData: data.data.timeData,
                    lastUpdateTime: data.timestamp
                };
            }

            // 通过事件总线通知图表组件
            if (this.$bus) {
                this.$bus.$emit('windowDataUpdate', data);
            }
        },

        /**
         * 超强节流的WebSocket设备信息更新处理
         */
        handleWebSocketDeviceInfoUpdateUltraThrottled(data) {
            if (!data || !Array.isArray(data)) return;

            console.log('📊 收到WebSocket设备信息更新（超强节流版本），设备数量:', data.length);

            // 仅处理当前设备，完全忽略其他设备
            const currentDeviceData = data.find(item => item.deviceId === this.currentDevice.id);

            if (currentDeviceData) {
                // 仅为当前设备进行最小化处理
                this.handleWebSocketAccelerationDataMinimal(currentDeviceData);

                // 立即触发当前设备图表更新
                console.log('🎯 当前设备数据更新（超强节流）:', currentDeviceData.deviceId);
                this.$nextTick(() => {
                    if (this.$bus) {
                        this.$bus.$emit('accelerationDataUpdate', {
                            deviceId: currentDeviceData.deviceId,
                            data: currentDeviceData,
                            timestamp: currentDeviceData.collectTime || Date.now()
                        });
                    }
                });
            }

            // 完全忽略其他设备，避免任何额外处理
            console.log('📊 其他设备数据已忽略，避免性能影响');
        },

        /**
         * 最小化的WebSocket加速度数据处理
         */
        handleWebSocketAccelerationDataMinimal(data) {
            if (!data || !data.deviceId) return;

            // 仅为当前设备输出日志
            if (data.deviceId === this.currentDevice.id) {
                console.log('📊 处理当前设备最小化数据:', data.deviceId);
            }

            // 使用数据管理器处理实时数据
            if (this.chartDataManager) {
                this.chartDataManager.addRealtimeData(data.deviceId, data);
            }

            // 仅为当前设备进行最小化节流
            if (data.deviceId === this.currentDevice.id) {
                const now = Date.now();
                const lastUpdate = this._currentDeviceLastUpdate || 0;

                // 当前设备使用100ms节流，保证波形图流畅
                if (now - lastUpdate >= 100) {
                    this._currentDeviceLastUpdate = now;
                    this.updateDeviceAccelerationDataFromWebSocket(data);
                }
            }
            // 完全忽略非当前设备
        },

        /**
         * 处理WebSocket设备信息更新（超强节流版本：解决周期性卡顿）
         */
        handleWebSocketDeviceInfoUpdate(data) {
            if (!data || !Array.isArray(data)) return;

            // 超强节流：最多每2秒处理一次批量数据
            const now = Date.now();
            const lastBatchProcess = this._lastBatchProcess || 0;
            if (now - lastBatchProcess < 2000) {
                // 跳过过于频繁的批量处理
                console.log('📊 跳过频繁的WebSocket批量处理');
                return;
            }
            this._lastBatchProcess = now;

            console.log('📊 收到WebSocket设备信息更新，设备数量:', data.length);

            // 立即提取当前设备数据，其他数据异步处理
            const currentDeviceData = data.find(item => item.deviceId === this.currentDevice.id);

            // 当前设备数据立即处理，保证波形图实时性
            if (currentDeviceData) {
                this.handleWebSocketAccelerationData(currentDeviceData);

                // 立即触发当前设备图表更新
                console.log('🎯 当前设备数据更新，触发图表刷新:', currentDeviceData.deviceId);
                this.$nextTick(() => {
                    if (this.$bus) {
                        this.$bus.$emit('accelerationDataUpdate', {
                            deviceId: currentDeviceData.deviceId,
                            data: currentDeviceData,
                            timestamp: currentDeviceData.collectTime || Date.now()
                        });
                    }
                });
            }

            // 大幅减少其他设备的处理频率
            if (data.length > 1) {
                this.scheduleAsyncDeviceProcessingThrottled(data);
            }
        },

        /**
         * 超强节流的异步设备处理（解决周期性卡顿）
         */
        scheduleAsyncDeviceProcessingThrottled(allData) {
            // 仅处理故障设备，忽略其他设备
            const criticalDevices = allData.filter(item =>
                item.status === '故障' || item.status === '异常'
            );

            if (criticalDevices.length === 0) {
                console.log('📊 无关键设备，跳过处理');
                return;
            }

            // 使用更长的延迟，减少处理频率
            setTimeout(() => {
                console.log('📊 处理关键设备:', criticalDevices.length);
                criticalDevices.forEach(deviceInfo => {
                    if (deviceInfo.deviceId) {
                        this.handleWebSocketAccelerationData(deviceInfo);
                    }
                });
            }, 5000); // 延迟5秒处理
        },

        /**
         * 调度异步设备处理，最小化主线程影响
         */
        scheduleAsyncDeviceProcessing(allData) {
            // 使用 MessageChannel 实现真正的异步处理
            if (window.MessageChannel) {
                const channel = new MessageChannel();
                channel.port2.onmessage = () => {
                    this.processDevicesInChunks(allData);
                };
                channel.port1.postMessage(null);
            } else {
                // 降级到 setTimeout
                setTimeout(() => {
                    this.processDevicesInChunks(allData);
                }, 0);
            }
        },

        /**
         * 分块处理设备数据，避免长时间阻塞
         */
        processDevicesInChunks(allData) {
            const chunkSize = 3; // 每次只处理3台设备
            const chunks = [];

            // 按优先级分组
            const criticalDevices = allData.filter(item =>
                item.status === '故障' || item.status === '异常'
            );
            const normalDevices = allData.filter(item =>
                item.deviceId !== this.currentDevice.id &&
                item.status !== '故障' &&
                item.status !== '异常'
            );

            // 关键设备优先处理
            for (let i = 0; i < criticalDevices.length; i += chunkSize) {
                chunks.push({
                    devices: criticalDevices.slice(i, i + chunkSize),
                    priority: 'critical'
                });
            }

            // 普通设备延后处理
            for (let i = 0; i < normalDevices.length; i += chunkSize) {
                chunks.push({
                    devices: normalDevices.slice(i, i + chunkSize),
                    priority: 'normal'
                });
            }

            // 分时处理每个块
            this.processChunksWithTimeSlicing(chunks);
        },

        /**
         * 时间切片处理，确保浏览器有时间处理其他任务
         */
        processChunksWithTimeSlicing(chunks) {
            if (chunks.length === 0) return;

            const processNextChunk = () => {
                if (chunks.length === 0) return;

                const chunk = chunks.shift();
                const startTime = performance.now();

                // 处理当前块
                chunk.devices.forEach(deviceInfo => {
                    if (deviceInfo.deviceId) {
                        this.handleWebSocketAccelerationData(deviceInfo);
                    }
                });

                const processingTime = performance.now() - startTime;
                console.log(`📊 处理${chunk.priority}设备块: ${chunk.devices.length}台, 耗时: ${processingTime.toFixed(2)}ms`);

                // 根据处理时间动态调整下次处理的延迟
                const delay = chunk.priority === 'critical' ? 5 : Math.max(10, processingTime * 2);

                // 继续处理下一块
                if (chunks.length > 0) {
                    setTimeout(processNextChunk, delay);
                }
            };

            // 开始处理
            processNextChunk();
        },



        /**
         * 处理WebSocket设备状态更新
         */
        handleWebSocketDeviceStatusUpdate(data) {
            console.log('📊 收到WebSocket设备状态数据:', data);

            // 更新设备状态数据
            if (data && Array.isArray(data)) {
                this.deviceStatusData = data;
                // 触发设备状态统计更新
                this.updateDeviceStatusFromWebSocket(data);
            }
        },

        /**
         * 从WebSocket数据更新设备状态统计
         */
        updateDeviceStatusFromWebSocket(statusData) {
            // 节流处理：避免频繁的状态统计计算
            const now = Date.now();
            const lastStatusUpdate = this._lastStatusUpdate || 0;
            if (now - lastStatusUpdate < 500) { // 500ms节流
                return; // 跳过过于频繁的更新
            }
            this._lastStatusUpdate = now;

            // 按latheName分组设备数据
            const latheNameGroups = {};

            statusData.forEach(device => {
                if (device.latheName) {
                    if (!latheNameGroups[device.latheName]) {
                        latheNameGroups[device.latheName] = {
                            devices: [],
                            status: '离线',
                            collectTime: device.collectTime
                        };
                    }

                    latheNameGroups[device.latheName].devices.push(device);

                    // 记录最新的时间
                    if (new Date(device.collectTime) > new Date(latheNameGroups[device.latheName].collectTime)) {
                        latheNameGroups[device.latheName].collectTime = device.collectTime;
                    }

                    // 标准化设备状态
                    const normalizedStatus = this.normalizeDeviceStatus(device.status);

                    // 按优先级更新状态: 故障 > 正常 > 待机 > 离线
                    if (normalizedStatus === '故障') {
                        latheNameGroups[device.latheName].status = '故障';
                    } else if (normalizedStatus === '正常' && latheNameGroups[device.latheName].status !== '故障') {
                        latheNameGroups[device.latheName].status = '正常';
                    } else if (normalizedStatus === '待机' &&
                              latheNameGroups[device.latheName].status !== '故障' &&
                              latheNameGroups[device.latheName].status !== '正常') {
                        latheNameGroups[device.latheName].status = '待机';
                    }
                }
            });

            // 更新latheNameSummaries
            this.latheNameSummaries = {};
            Object.keys(latheNameGroups).forEach(latheName => {
                this.latheNameSummaries[latheName] = {
                    status: latheNameGroups[latheName].status,
                    collectTime: latheNameGroups[latheName].collectTime
                };
            });

            // 统计各状态设备数量
            const stats = { normal: 0, warning: 0, waiting: 0, offline: 0 };

            Object.values(latheNameGroups).forEach(latheData => {
                switch (latheData.status) {
                    case '正常': stats.normal++; break;
                    case '故障': stats.warning++; break;
                    case '待机': stats.waiting++; break;
                    default: stats.offline++; break;
                }
            });

            // 计算离线设备数量
            stats.offline = this.totalDevices - (stats.normal + stats.warning + stats.waiting);

            // 更新设备状态统计
            this.deviceStatus = {
                normalCount: stats.normal,
                normalRate: Math.round((stats.normal / this.totalDevices) * 100),
                warningCount: stats.warning,
                warningRate: Math.round((stats.warning / this.totalDevices) * 100),
                waitingCount: stats.waiting,
                waitingRate: Math.round((stats.waiting / this.totalDevices) * 100),
                offlineCount: stats.offline,
                offlineRate: Math.round((stats.offline / this.totalDevices) * 100)
            };

            // 更新圆环进度条
            this.updateCircleProgress();

            // 更新健康评分
            this.healthScore = this.calculateHealthScore(latheNameGroups);

            // 更新最后更新时间
            this.dataStatus.lastUpdate = new Date().toLocaleTimeString();
        },

        /**
         * 处理WebSocket错误
         */
        handleWebSocketError(error) {
            console.error('WebSocket错误:', error);
            this.webSocketReconnectAttempts++;

            if (this.webSocketReconnectAttempts >= this.maxWebSocketReconnectAttempts) {
                console.log('❌ WebSocket重连次数超限，回退到HTTP轮询模式');
                this.fallbackToPollingMode();
            }
        },

        /**
         * 回退到HTTP轮询模式
         */
        fallbackToPollingMode() {
            console.log('🔄 回退到HTTP轮询模式');
            this.useWebSocket = false;

            // 清理WebSocket连接
            this.cleanupWebSocketAndWindowManager();

            // 启动HTTP轮询
            this.startDataUpdate();
        },

        /**
         * 清理WebSocket和滑动窗口管理器
         */
        cleanupWebSocketAndWindowManager() {
            console.log('🧹 清理WebSocket和滑动窗口管理器...');

            // 清理滑动窗口管理器
            if (this.accelerationWindowManager) {
                this.accelerationWindowManager.stop();
                this.accelerationWindowManager = null;
            }

            // 清理WebSocket连接
            if (this.webSocketService) {
                this.webSocketService.disconnect();
                this.webSocketService = null;
            }

            this.isWebSocketConnected = false;
            this.webSocketReconnectAttempts = 0;
        },

        /**
         * 切换设备时的WebSocket处理
         */
        handleDeviceSwitchForWebSocket(newDeviceId, oldDeviceId) {
            if (!this.useWebSocket || !this.webSocketService) return;

            // 取消订阅旧设备
            if (oldDeviceId) {
                this.unsubscribeDeviceData(oldDeviceId);
            }

            // 清空滑动窗口中的旧设备数据
            if (this.accelerationWindowManager && oldDeviceId) {
                this.accelerationWindowManager.clearDeviceData(oldDeviceId);
            }

            // 订阅新设备
            if (newDeviceId && this.isWebSocketConnected) {
                setTimeout(() => {
                    this.subscribeCurrentDeviceData();
                }, 100); // 短暂延迟确保设备信息已更新
            }
        },

        /**
         * 调试方法：手动测试数据更新
         */
        testDataUpdate() {
            console.log('🧪 开始测试数据更新...');

            // 模拟WebSocket数据
            const testData = {
                deviceId: this.currentDevice.id,
                latheName: this.currentDevice.latheName,
                xrms: Math.random() * 10 + 5,
                yrms: Math.random() * 10 + 5,
                zrms: Math.random() * 10 + 5,
                xpeak: Math.random() * 20 + 10,
                ypeak: Math.random() * 20 + 10,
                zpeak: Math.random() * 20 + 10,
                timestamp: Date.now()
            };

            console.log('🧪 模拟数据:', testData);
            this.handleWebSocketAccelerationData(testData);
        },

        /**
         * 调试方法：模拟真实WebSocket消息
         */
        testWebSocketMessage() {
            console.log('🧪 开始测试WebSocket消息处理...');

            // 模拟真实的WebSocket消息格式
            const mockMessage = {
                type: "DEVICE_INFO_UPDATE",
                data: [
                    {
                        deviceId: this.currentDevice.id,
                        collectTime: Date.now(),
                        temperature: 25.0 + Math.random() * 10,
                        latheName: this.currentDevice.latheName,
                        putPlace: this.currentDevice.putPlace || "SP1主轴电机驱动端",
                        zpeak: Math.random() * 15 + 5,
                        ypeak: Math.random() * 15 + 5,
                        xrms: Math.random() * 8 + 2,
                        xpeak: Math.random() * 15 + 5,
                        zrms: Math.random() * 8 + 2,
                        yrms: Math.random() * 8 + 2
                    }
                ],
                timestamp: Date.now()
            };

            console.log('🧪 模拟WebSocket消息:', mockMessage);

            // 直接调用WebSocket消息处理器
            if (this.webSocketService) {
                this.webSocketService.handleMessage(mockMessage);
            } else {
                // 如果WebSocket服务不可用，直接调用处理方法
                this.handleWebSocketDeviceInfoUpdate(mockMessage.data);
            }
        },

        /**
         * 调试方法：启动连续数据流测试
         */
        startContinuousDataTest() {
            console.log('🧪 启动连续数据流测试...');

            if (this.continuousTestTimer) {
                clearInterval(this.continuousTestTimer);
            }

            let counter = 0;
            this.continuousTestTimer = setInterval(() => {
                counter++;

                // 模拟数据变化趋势
                const baseRms = 5;
                const basePeak = 10;
                const variation = Math.sin(counter * 0.1) * 2; // 正弦波变化
                const noise = (Math.random() - 0.5) * 1; // 随机噪声

                const mockMessage = {
                    type: "DEVICE_INFO_UPDATE",
                    data: [
                        {
                            deviceId: this.currentDevice.id,
                            collectTime: Date.now(),
                            temperature: 25.0 + Math.random() * 5,
                            latheName: this.currentDevice.latheName,
                            putPlace: this.currentDevice.putPlace || "SP1主轴电机驱动端",
                            xrms: Math.max(0, baseRms + variation + noise),
                            yrms: Math.max(0, baseRms + variation * 0.8 + noise),
                            zrms: Math.max(0, baseRms + variation * 1.2 + noise),
                            xpeak: Math.max(0, basePeak + variation * 2 + noise),
                            ypeak: Math.max(0, basePeak + variation * 1.5 + noise),
                            zpeak: Math.max(0, basePeak + variation * 2.5 + noise)
                        }
                    ],
                    timestamp: Date.now()
                };

                console.log(`🧪 连续测试 #${counter}:`, {
                    xrms: mockMessage.data[0].xrms.toFixed(2),
                    yrms: mockMessage.data[0].yrms.toFixed(2),
                    zrms: mockMessage.data[0].zrms.toFixed(2)
                });

                // 处理消息
                if (this.webSocketService) {
                    this.webSocketService.handleMessage(mockMessage);
                } else {
                    this.handleWebSocketDeviceInfoUpdate(mockMessage.data);
                }
            }, 1000); // 每秒一次

            console.log('✅ 连续数据流测试已启动，每秒发送一次数据');
            console.log('💡 使用 window.stopContinuousDataTest() 停止测试');
        },

        /**
         * 调试方法：停止连续数据流测试
         */
        stopContinuousDataTest() {
            if (this.continuousTestTimer) {
                clearInterval(this.continuousTestTimer);
                this.continuousTestTimer = null;
                console.log('🛑 连续数据流测试已停止');
            } else {
                console.log('⚠️ 没有正在运行的连续测试');
            }
        },

        /**
         * 判断是否应该滑动窗口
         * @param {Object} deviceAccData 设备加速度数据
         * @param {number} collectTime 数据收集时间
         * @returns {boolean} 是否应该滑动窗口
         */
        shouldSlideWindowForDevice(deviceAccData, collectTime) {
            const now = Date.now();
            const timeSinceLastUpdate = now - (deviceAccData.lastUpdateTime || 0);

            // 如果是首次更新，不滑动窗口（保持历史数据）
            if (!deviceAccData.lastUpdateTime && deviceAccData.hasHistoricalData) {
                console.log('📊 首次实时更新，保持历史数据');
                return false;
            }

            // 如果时间间隔超过5秒，则滑动窗口
            if (timeSinceLastUpdate >= 5000) {
                console.log('📈 时间间隔超过5秒，滑动窗口');
                return true;
            }

            // 检查是否有历史数据
            const hasHistoricalData = deviceAccData.hasHistoricalData ||
                                    deviceAccData.timeData.some(time => time && time !== null);

            // 如果没有历史数据，直接滑动窗口
            if (!hasHistoricalData) {
                console.log('📊 无历史数据，滑动窗口');
                return true;
            }

            // 检查新数据的时间是否比最新的历史数据更新
            const lastTimeString = deviceAccData.timeData[59];
            if (lastTimeString) {
                const lastTime = this.parseTimeString(lastTimeString);
                const newTime = new Date(collectTime);

                // 如果新数据时间比最新历史数据晚超过30秒，则滑动窗口
                if (lastTime && newTime.getTime() - lastTime.getTime() > 30000) {
                    console.log('📈 新数据时间超前30秒，滑动窗口');
                    return true;
                }
            }

            console.log('📊 保持历史数据，不滑动窗口');
            return false;
        },

        /**
         * 找到合适的插入位置
         * @param {Array} timeData 时间数据数组
         * @param {string} newTimeString 新时间字符串
         * @param {number} collectTime 收集时间戳
         * @returns {number} 插入位置索引，-1表示找不到合适位置
         */
        findInsertPosition(timeData, newTimeString, collectTime) {
            const newTime = new Date(collectTime);

            // 从后往前查找合适的插入位置
            for (let i = timeData.length - 1; i >= 0; i--) {
                if (!timeData[i] || timeData[i] === null) {
                    continue;
                }

                const existingTime = this.parseTimeString(timeData[i]);
                if (existingTime && newTime.getTime() >= existingTime.getTime()) {
                    // 如果新时间比现有时间更新或相等，插入到下一个位置
                    return Math.min(i + 1, timeData.length - 1);
                }
            }

            // 如果没找到合适位置，返回最后一个位置
            return timeData.length - 1;
        },

        /**
         * 解析时间字符串为Date对象
         * @param {string} timeString 时间字符串 (HH:mm:ss)
         * @returns {Date|null} Date对象或null
         */
        parseTimeString(timeString) {
            if (!timeString || typeof timeString !== 'string') {
                return null;
            }

            try {
                const today = new Date();
                const [hours, minutes, seconds] = timeString.split(':').map(Number);

                if (isNaN(hours) || isNaN(minutes) || isNaN(seconds)) {
                    return null;
                }

                const date = new Date(today.getFullYear(), today.getMonth(), today.getDate(), hours, minutes, seconds);
                return date;
            } catch (error) {
                console.warn('解析时间字符串失败:', timeString, error);
                return null;
            }
        },

        /**
         * 调试方法：测试历史数据和实时数据融合
         */
        testHistoricalDataIntegration() {
            console.log('🧪 开始测试历史数据和实时数据融合...');

            const deviceId = this.currentDevice.id;

            // 首先加载历史数据
            this.loadHistoricalAccelerationData(deviceId).then(() => {
                console.log('✅ 历史数据加载完成');

                // 等待1秒后开始发送实时数据
                setTimeout(() => {
                    console.log('🔄 开始发送实时数据...');

                    let counter = 0;
                    const testTimer = setInterval(() => {
                        counter++;

                        // 模拟实时数据（时间比历史数据更新）
                        const mockMessage = {
                            type: "DEVICE_INFO_UPDATE",
                            data: [
                                {
                                    deviceId: deviceId,
                                    collectTime: Date.now(), // 使用当前时间
                                    temperature: 25.0 + Math.random() * 5,
                                    latheName: this.currentDevice.latheName,
                                    putPlace: this.currentDevice.putPlace || "SP1主轴电机驱动端",
                                    xrms: 5 + Math.sin(counter * 0.2) * 2 + Math.random(),
                                    yrms: 5 + Math.cos(counter * 0.2) * 2 + Math.random(),
                                    zrms: 5 + Math.sin(counter * 0.3) * 1.5 + Math.random(),
                                    xpeak: 10 + Math.sin(counter * 0.2) * 4 + Math.random() * 2,
                                    ypeak: 10 + Math.cos(counter * 0.2) * 4 + Math.random() * 2,
                                    zpeak: 10 + Math.sin(counter * 0.3) * 3 + Math.random() * 2
                                }
                            ],
                            timestamp: Date.now()
                        };

                        console.log(`🧪 发送实时数据 #${counter}`);

                        // 处理消息
                        if (this.webSocketService) {
                            this.webSocketService.handleMessage(mockMessage);
                        } else {
                            this.handleWebSocketDeviceInfoUpdate(mockMessage.data);
                        }

                        // 发送10次后停止
                        if (counter >= 10) {
                            clearInterval(testTimer);
                            console.log('✅ 历史数据和实时数据融合测试完成');
                        }
                    }, 2000); // 每2秒发送一次
                }, 1000);
            }).catch(error => {
                console.error('❌ 历史数据加载失败:', error);
            });
        }
    },
    watch: {
        deviceStatusData: {
            handler(newData) {
                console.log('设备数据已更新:', newData)
                // 可以在这里添加数据变化的处理逻辑
            },
            deep: true
        }
    }
}
</script>


<style lang="scss" scoped>
.index {
    width: 100%;
    height: 100vh;
    // 修改背景图片路径写法
    background: url('../../../assets/detect/background.jpg') no-repeat center center;
    background-size: cover;
    color: #fff;
    overflow: hidden;
    display: flex;

    &.fullscreen-mode {
        // 同步修改全屏模式下的背景图片路径
        background: url('../../../assets/detect/background.jpg') no-repeat center center;
        background-size: cover;

        .dashboard {
            width: 100vw;
            height: 100vh;
            padding: 0;
        }

    }
}

.left-sidebar {
    &.hidden {
        display: none;
    }
}

// 全屏时的样式
:fullscreen,
:-webkit-full-screen,
:-moz-full-screen,
:-ms-fullscreen {
    .index {
        // 同步修改其他全屏模式下的背景图片路径
        background: url('../../../assets/detect/background.jpg') no-repeat center center;
        background-size: cover;
    }
}

.dashboard {
    position: relative; // 添加这行
    width: 100%;
    height: 100%;
    padding: 10px;
    display: flex;
    flex-direction: column;
}

// Header 样式已移动到 HeaderSection 组件中

.content {
    display: grid;
    grid-template-columns: 22% 54% 22%;
    grid-template-rows: 58% 40%; // 调整网格比例，增加下方区域高度
    gap: 15px; // 减少间距以获得更多空间
    padding: 0 15px 0 5px;
    height: calc(100vh - 64px);
}

// 左侧模块样式已移动到对应组件中

// 监测记录样式已移动到 MonitorLog 组件中

// 中间模块样式已移动到对应组件中

// 设备网格样式已移动到 DeviceGrid 组件中






// 右上模块样式已移动到对应组件中
// DataStatus 样式已移动到 DataStatus 组件中

@media screen and (min-width: 1280px) and (min-height: 720px) {
    .dashboard {
        min-width: 1280px;
        min-height: 720px;
    }
}

@media screen and (max-height: 900px) {
    .header {
        height: 50px;

        h1 {
            font-size: 40px;
        }

        .tabs .tab {
            padding: 1px 10px;
        }
    }

    .chart {
        height: 150px;
    }

    .circle-progress {
        width: 100px;
        height: 100px;
    }
}

// 修改全屏样式混入
@mixin fullscreen-styles {
    background: url('../../../assets/detect/background.jpg') no-repeat center center !important;
    background-size: cover !important;

    .dashboard {
        height: 100vh !important;
        width: 100vw !important;
        padding: 15px;
        margin: 0;

        .content {
            display: grid;
            grid-template-columns: 22% 54% 22%;
            grid-template-rows: 58% 40%; // 调整网格比例，增加下方区域高度
            gap: 15px; // 减少间距以获得更多空间
            padding: 0 15px;
            height: calc(100vh - 54px);

        }
    }

    .circle-progress {
        &::after {
            background: rgb(3, 12, 49); // 使用相同的深蓝色背景
        }
    }

    .health-score {
        .score-content {
            .score-circle {
                width: 180px;
                height: 180px;
                margin-left: 30px;
                margin-top: 10px; // 减小顶部间距
                margin-bottom: 20px;
            }

            .score-details {
                margin-left: 20px;
                margin-top: -70px;

                .detail-item {
                    font-size: 16px;
                    margin-bottom: 5px;
                }
            }
        }
    }

    .header {
        .title-section {
            h1 {
                font-size: 48px; // 增大字号
                margin-top: 40px; // 增加顶部间距
                margin-bottom: 20px; // 添加底部间距

            }
        }
    }

    .comparison-chart {
        #comparisonChart {
            transform: scale(1.2);
            transform-origin: center; // 从中心点放大
            margin-top: 30px !important; // 适当下移以保持居中
            margin-left: 7px !important;

            .gauge-detail {
                .rich-text {
                    .title {
                        font-size: 22px !important; // 放大标题文字
                        padding: 0 0 20px 0;
                    }

                    .value {
                        font-size: 42px !important; // 放大数值文字
                        padding: 0 0 20px 0;
                    }

                    .device {
                        font-size: 20px !important; // 放大设备数量文字
                    }
                }
            }
        }
    }

    .comparison-chart {
        .chart-content {
            padding: 0 40px; // 全屏模式下增加内边距

            #comparisonChart {
                transform: scale(1.2);
                transform-origin: center;
            }

            .status-text {
                padding-left: 40px; // 全屏模式下增加文字区域的左边距

                .title {
                    font-size: 28px; // 全屏模式下增大字号
                }

                .subtitle {
                    font-size: 18px; // 全屏模式下增大字号
                }
            }
        }
    }


    .center-module {
        .device-grid {
            width: 605px;
            height: 605px;
          transform: rotate(328deg) scale(0.85);
            transform-origin: center;
          // 向下移动
          // 向右移动
          margin: 20px auto auto 130px;

          // 调整设备图标在全屏模式下的位置
            .device-item {

                // 第一行位置调整
                &:nth-child(-n+7) {
                    top: 60px; // 调整顶部距离
                    left: -140px; // 调整左侧距离
                }

                // 第二行位置调整
                &:nth-child(n+8):nth-child(-n+14) {
                    top: 30px;
                    left: -90px;
                }

                // 第三行位置调整
                &:nth-child(n+15):nth-child(-n+21) {
                    top: 0;
                    left: -20px;
                }

                // 第四行位置调整
                &:nth-child(n+22):nth-child(-n+28) {
                    top: -40px;
                    left: 40px;
                }

                // 第五行位置调整
                &:nth-child(n+29):nth-child(-n+35) {
                    top: -80px;
                    left: 110px;
                }
            }
        }
    }
}

// 应用全屏样式到各个浏览器
:fullscreen {
    @include fullscreen-styles;
}

:-webkit-full-screen {
    @include fullscreen-styles;
}

:-moz-full-screen {
    @include fullscreen-styles;
}

:-ms-fullscreen {
    @include fullscreen-styles;
}

// 全屏按钮样式
.fullscreen-btn {
    width: 28px;
    height: 28px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    color: #8f9bb3;
    background: rgba(3, 12, 49, 0.6);
    border: 1px solid rgba(28, 89, 156, 0.3);
    border-radius: 10px;
    margin-left: 12px;
    transition: all 0.3s ease;

    &:hover {
        color: #fff;
        background: rgba(0, 120, 255, 0.2);
        transform: scale(1.05);
    }

    i {
        font-size: 18px;
    }
}

// 统一的标题样式
.chart-title {
    left: 10px;
    height: 40px; // 增加高度
    padding: 0 20px; // 增加左右内边距
    font-size: 17px; // 调整字体大小
    color: #fff; // 改为白色
    display: flex;
    align-items: center;
    position: relative; // 为左侧装饰做准备

    // 左侧装饰条
    &::before {
        content: '';
        position: absolute;
        left: 0;
        top: 50%;
        transform: translateY(-50%);
        width: 3px;
        height: 16px;
        background: #ff9900; // 橙色装饰条
        border-radius: 0 2px 2px 0;
    }
}

// 调整各个模块的标题样式
.stat-card,
.usage-chart,
.comparison-chart,
.monitor-log,
.acceleration-chart,
.health-score,
.running-rate,
.shift-rate,

// 加速度数据图表的标题样式调整
.acceleration-chart .chart-title {
    justify-content: space-between; // 两端对齐，因为右侧有状态显示

    .device-status {
        font-size: 12px;
        padding: 2px 12px;
        border-radius: 10px;
        background: rgba(0, 0, 0, 0.2);
    }
}

// 调整图表容器，为新的标题高度做适配
.chart-content,
#accelerationChart,
#comparisonChart,
#usageChart,

.acceleration-chart {
    position: relative; // 添加相对定位

    .chart-title {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .chart-controls {
            display: flex;
            align-items: center;
            gap: 15px;

            .switch-buttons {
                display: flex;
                gap: 8px;

                .switch-btn {
                    padding: 4px 12px;
                    border: 1px solid rgba(255, 255, 255, 0.6);
                    border-radius: 4px;
                    background: transparent;
                    color: rgba(255, 255, 255, 0.6);
                    cursor: pointer;
                    font-size: 12px;
                    transition: all 0.3s ease;
                    min-width: 60px;
                    text-align: center;

                    &:hover {
                        border-color: #fff;
                        color: #fff;
                    }

                    &.active {
                        background: rgba(255, 255, 255, 0.1);
                        border-color: #fff;
                        color: #fff;
                    }
                }
            }
        }
    }
}

// 其他浏览器全屏样式
:-webkit-full-screen,
:-moz-full-screen,
.acceleration-chart {
    .chart-title {
        .chart-controls {
            .device-status {
                &.normal {
                    background: rgba(0, 255, 76, 0.2); // 正常状态 - 绿色背景
                    color: #00ff4c;
                }

                &.warning {
                    background: rgba(255, 43, 43, 0.2); // 故障状态 - 红色背景
                    color: #ff2b2b;
                }

                &.waiting {
                    background: rgba(255, 179, 0, 0.2); // 待机状态 - 黄色背景
                    color: #ffb300;
                }

                &.offline {
                    background: rgba(128, 128, 128, 0.2); // 离线状态 - 灰色背景
                    color: #808080;
                }
            }
        }
    }
}

// 添加或修改样式
.chart-title {
    height: 40px;
    padding: 0 20px;
    font-size: 17px;
    color: #fff;
    display: flex;
    align-items: center;
    justify-content: space-between; // 使状态标签靠右

    .status-tag {
        padding: 2px 8px;
        border-radius: 4px;
        font-size: 12px;
        min-width: 48px;
        text-align: center;
        margin-top: 3px;
        margin-left: 20px; // 与左边文字保持固定间距
        // 移除 margin-right 和 margin-left: auto

        &.normal {
            background: #20b84e;
            color: #ffffff;
        }

        &.warning {
            background: #ff2b2b;
            color: #ffffff;
        }

        &.waiting {
            background: #ffb300;
            color: #ffffff;
        }

        &.offline {
            background: #808080;
            color: #ffffff;
        }
    }
}

// 基础样式，作为所有状态下的标准样式
.health-score {
    .score-content {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        height: calc(100% - 40px);
        padding: 20px;

        .score-circle {
            width: 180px !important;
            height: 180px !important;
        }

        .score-details {
            width: 100%;
            text-align: center;
            margin-top: 10px !important;  // 固定的顶部间距

            .detail-item {
                font-size: 16px;
                line-height: 1.6;
                color: rgba(255, 255, 255, 0.9);
            }
        }
    }
}

// 全屏时只修改间距
.fullscreen-mode {
    .health-score {
        .score-content {
            .score-circle {
                margin: 0 auto !important;  // 全屏时增加底部间距
            }

            .score-details {
                margin-top: 25px !important;  // 全屏时增加顶部间距
            }
        }
    }
}

// 基础样式保持不变
.health-score {
    .score-content {
        .score-circle {
            width: 180px !important;
            height: 180px !important;
        }
    }
}

// 全屏时修改尺寸和间距
.fullscreen-mode {
    .health-score {
        .score-content {

            .score-circle {
                width: 300px;
                height: 300px;

            }

            .score-details {
                top: 40px;  // 通过相对定位向下移动文字
                width: 100%;
                text-align: center;

                .detail-item {
                    font-size: 16px;
                    margin-top: 30px;
                    color: rgba(255, 255, 255, 0.9);
                }
            }
        }
    }
}

// 其他浏览器全屏样式
:fullscreen,
:-webkit-full-screen,
:-moz-full-screen,
:-ms-fullscreen {
    @extend .fullscreen-mode;
}

// 全屏时修改尺寸和位置
.fullscreen-mode {
    .health-score {
        .score-content {
            position: relative;  // 添加相对定位作为参考

            .score-circle {
                width: 300px;
                height: 300px;
                position: relative;   // 添加相对定位
                // left: -40px;         // 向左移动水波图
                margin: 0 auto;      // 保持其他方向的间距
            }

            .score-details {
                top: 40px;
                width: 100%;
                text-align: center;

                .detail-item {
                    font-size: 16px;
                    margin-top: 30px;

                    color: rgba(255, 255, 255, 0.9);
                }
            }
        }
    }
}

/* 全屏模式下的按钮样式调整 */
.fullscreen-mode {
    .center-module {
        .workshop-buttons {
            top: 30px;
            left: 50px; /* 调整左侧距离 */

            .switch-buttons {
                .switch-btn {
                    padding: 4px 12px; // 全屏模式下稍微大一点
                    font-size: 14px; // 全屏模式下稍微大一点
                    min-width: 70px; // 全屏模式下稍微宽一点
                }
            }
        }
    }
}

// 右下模块样式已移动到对应组件中

/* 全屏模式下的样式调整 */
@mixin fullscreen-styles {
    // ... 其他全屏样式 ...

    .right-bottom-module {
        .acceleration-chart {
            // 标题样式
            .chart-title {
                height: 40px; // 调整标题高度
                font-size: 20px; // 调整标题字体大小
                margin-bottom: 5px; // 调整标题底部间距
            }

            // 图表容器样式
            .chart-container {
                height: calc(100% - 15px); // 调整容器高度
                padding: 10px 0 20px 0; // 增加底部内边距为20px

                #accelerationChart {
                    // 这里可以通过CSS变换调整图表的大小和位置
                    transform: scaleY(1.1); // Y轴方向放大
                    transform-origin: center center; // 从中心点开始变换
                    height: calc(100% - 10px) !important; // 底部预留10px空间
                }
            }
        }

        // 全屏模式下优化加速图显示
        .right-bottom-module {
            .acceleration-chart {
                height: 100%;

                .chart-container {
                    height: calc(100% - 40px);

                    #accelerationChart {
                        height: 100% !important;
                    }
                }
            }
        }
    }
}

// 应用全屏样式到各个浏览器
:fullscreen {
    @include fullscreen-styles;
}

:-webkit-full-screen {
    @include fullscreen-styles;
}

:-moz-full-screen {
    @include fullscreen-styles;
}

:-ms-fullscreen {
    @include fullscreen-styles;
}

// 对应类全屏模式
.fullscreen-mode {
    @include fullscreen-styles;
}

/* 调整加速度图表标题和按钮样式 */
.acceleration-chart {
    .chart-title {
        display: flex;
        align-items: center;
        padding: 0 20px;
        height: 40px;
        position: relative;

        /* 添加标题文本样式 */
        .title-text {
            font-size: 17px;
            color: #fff;
            margin-right: 20px; /* 确保标题和控件之间有空间 */
            white-space: nowrap; /* 防止标题换行 */
        }

        /* 左侧装饰条的位置调整 */
        &::before {
            content: '';
            position: absolute;
            left: 0;
            top: 50%;
            transform: translateY(-50%);
            width: 3px;
            height: 16px;
            background: #ff9900;
            border-radius: 0 2px 2px 0;
        }

        .chart-controls {
            display: flex;
            align-items: center;
            gap: 10px; /* 减少控件之间的间距 */
            flex-wrap: nowrap; /* 防止控件换行 */
            flex: 1; /* 占据剩余空间 */
            justify-content: flex-start; /* 从左向右排列 */
            overflow-x: auto; /* 当控件太多时允许横向滚动 */
            padding-bottom: 5px; /* 留出滚动条空间 */

            /* 隐藏滚动条但保留功能 */
            &::-webkit-scrollbar {
                height: 2px;
            }

            &::-webkit-scrollbar-track {
                background: rgba(0, 0, 0, 0.1);
            }

            &::-webkit-scrollbar-thumb {
                background: rgba(255, 255, 255, 0.3);
            }

            .status-tag {
                padding: 2px 8px;
                border-radius: 4px;
                font-size: 12px;
                min-width: auto; /* 移除最小宽度限制 */
                text-align: center;
                white-space: nowrap; /* 防止文字换行 */

                &.normal {
                    background: #20b84e;
                    color: #ffffff;
                }

                &.warning {
                    background: #ff2b2b;
                    color: #ffffff;
                }

                &.waiting {
                    background: #ffb300;
                    color: #ffffff;
                }

                &.offline {
                    background: #808080;
                    color: #ffffff;
                }
            }

            /* 安装位置下拉选择器样式 */
            .position-dropdown {
                margin-right: 5px;

                .el-dropdown-link {
                    display: inline-block;
                    padding: 2px 10px;
                    border: 1px solid rgba(255, 255, 255, 0.6);
                    border-radius: 4px;
                    background: transparent;
                    color: rgba(255, 255, 255, 0.6);
                    cursor: pointer;
                    font-size: 12px;
                    white-space: nowrap;
                    transition: all 0.3s ease;

                    &:hover {
                        border-color: #fff;
                        color: #fff;
                        background: rgba(255, 255, 255, 0.1);
                    }
                }
            }

            /* 按钮组样式 */
            .switch-buttons {
                display: flex;
                gap: 5px; /* 减小按钮间距 */

                &.position-buttons {
                    margin-right: 5px; /* 在位置按钮和类型按钮之间添加间距 */
                }

                .switch-btn {
                    padding: 2px 10px; /* 减小内边距 */
                    border: 1px solid rgba(255, 255, 255, 0.6);
                    border-radius: 4px;
                    background: transparent;
                    color: rgba(255, 255, 255, 0.6);
                    cursor: pointer;
                    font-size: 12px;
                    transition: all 0.3s ease;
                    min-width: auto; /* 移除最小宽度限制 */
                    max-width: none; /* 移除最大宽度限制 */
                    text-align: center;
                    white-space: nowrap; /* 防止按钮文字换行 */

                    &:hover {
                        border-color: #fff;
                        color: #fff;
                    }

                    &.active {
                        background: rgba(255, 255, 255, 0.1);
                        border-color: #fff;
                        color: #fff;
                    }
                }
            }
        }
    }
}

/* Element UI 下拉菜单样式覆盖 */
.el-dropdown-menu {
    background: rgba(3, 12, 49, 0.95) !important;
    border: 1px solid rgba(28, 89, 156, 0.5) !important;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.3) !important;

    .el-dropdown-menu__item {
        color: rgba(255, 255, 255, 0.6) !important;
        font-size: 12px !important;
        padding: 5px 15px !important;

        &:hover {
            background-color: rgba(255, 255, 255, 0.1) !important;
            color: #fff !important;
        }

        &.active-position {
            background-color: rgba(0, 160, 233, 0.2) !important;
            color: #fff !important;

            &::before {
                content: '✓ ';
                color: #00a0e9;
            }
        }
    }
}

// 全屏模式下的下拉菜单样式
:fullscreen, :-webkit-full-screen, :-moz-full-screen, :-ms-fullscreen, .fullscreen-mode {
    .el-dropdown-menu {
        background: rgba(3, 12, 49, 0.95) !important;
        border: 1px solid rgba(28, 89, 156, 0.7) !important;

        .el-dropdown-menu__item {
            font-size: 14px !important;
            padding: 8px 20px !important;
        }
    }
}

/* 全屏模式下调整按钮样式 */
@mixin fullscreen-styles {
    // ... 其他全屏样式保持不变

    .acceleration-chart {
        .chart-title {
            height: 50px; /* 全屏模式下增加标题高度 */

            .title-text {
                font-size: 20px; /* 全屏模式下增大标题字体 */
                margin-right: 30px; /* 全屏模式下增加标题和控件之间的间距 */
            }

            .chart-controls {
                gap: 15px; /* 全屏模式下增加控件间距 */

                .status-tag {
                    padding: 3px 10px; /* 全屏模式下增大状态标签内边距 */
                    font-size: 14px; /* 全屏模式下增大状态标签字体 */
                }

                .position-dropdown {
                    .el-dropdown-link {
                        padding: 3px 12px; /* 全屏模式下增大按钮内边距 */
                        font-size: 14px; /* 全屏模式下增大按钮字体 */
                    }
                }

                .switch-buttons {
                    gap: 8px; /* 全屏模式下增加按钮间距 */

                    .switch-btn {
                        padding: 3px 12px; /* 全屏模式下增大按钮内边距 */
                        font-size: 14px; /* 全屏模式下增大按钮字体 */
                    }
                }
            }
        }
    }

    // 全屏模式下的悬浮提示框样式增强
    .device-item {
        .device-tooltip {
            min-width: 260px; // 全屏模式下增加宽度
            padding: 20px 25px; // 全屏模式下增加内边距
            border-radius: 16px; // 全屏模式下增加圆角

            &::before {
                // 全屏模式下的光效更强
                background: radial-gradient(circle at 30% 30%, rgba(255, 255, 255, 0.15), transparent 80%);
            }

            span {
                &:first-child {
                    font-size: 22px; // 全屏模式下增大标题字体
                    margin-bottom: 12px; // 全屏模式下增加底部间距
                    padding-bottom: 12px; // 全屏模式下增加内边距
                }

                &.status-line {
                    font-size: 18px; // 全屏模式下增大状态字体

                    &::before {
                        width: 10px; // 全屏模式下增大状态图标
                        height: 10px; // 全屏模式下增大状态图标
                        margin-right: 10px; // 全屏模式下增加右侧间距
                    }
                }
            }

            // 全屏模式下增加额外信息区域
            &.auto-tooltip-active::after {
                content: attr(data-extra-info);
                display: block;
                margin-top: 10px;
                font-size: 14px;
                opacity: 0.85;
                text-align: center;
                border-top: 1px solid rgba(255, 255, 255, 0.3);
                padding-top: 8px;
            }
        }
    }
}

// 应用全屏样式
:fullscreen, :-webkit-full-screen, :-moz-full-screen, :-ms-fullscreen, .fullscreen-mode {
    @include fullscreen-styles;
}

/* 适应小屏幕 */
@media screen and (max-width: 1366px) {
    .acceleration-chart {
        .chart-title {
            .title-text {
                font-size: 15px; /* 小屏幕下减小标题字体 */
                margin-right: 15px; /* 小屏幕下减小间距 */
            }

            .chart-controls {
                gap: 8px; /* 小屏幕下减小控件间距 */

                .position-dropdown {
                    .el-dropdown-link {
                        padding: 1px 8px; /* 小屏幕下减小按钮内边距 */
                        font-size: 11px; /* 小屏幕下减小按钮字体 */
                    }
                }

                .switch-buttons {
                    .switch-btn {
                        padding: 1px 8px; /* 小屏幕下减小按钮内边距 */
                        font-size: 11px; /* 小屏幕下减小按钮字体 */
                    }
                }
            }
        }
    }
}

/* 添加图表容器样式 */
.chart-container {
    height: calc(100% - 40px);
    width: 100%;
    overflow: visible; /* 确保变换不会被裁剪 */
    padding-bottom: 10px; /* 底部预留10px空间 */
}

/* 无数据容器样式 */
.no-data-container {
    height: calc(100% - 40px);
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
}

/* 新增：监测记录滑动动画 */
.log-slide-enter-active,
.log-slide-leave-active {
    transition: all 0.5s cubic-bezier(0.23, 1, 0.32, 1); /* 修改缓动函数 */
}

.log-slide-enter-from /* Vue 3 (or enter for Vue 2) */ {
    opacity: 0;
    transform: scale(0.7) translateY(-30px) rotateX(20deg); /* 增加旋转和调整的进入效果 */
}

.log-slide-leave-to /* Vue 3 (or leave-to for Vue 2) */ {
    opacity: 0;
    transform: scale(0.7) translateY(30px) rotateX(-20deg); /* 增加旋转和调整的离开效果 */
}

.log-slide-leave-active {
    position: absolute; /* 离开时脱离文档流，防止抖动 */
    width: calc(100% - 20px); /* 减去padding的宽度 */
}

.log-slide-move {
    transition: transform 0.8s ease-in-out;
}

/* AI 按钮闪动 */
@keyframes aiPulse {
    0%, 100% { transform: scale(1); opacity: 0.9; }
    50% { transform: scale(1.15); opacity: 1; }
}

.ai-tooltip-btn {
    display: inline-flex;
    margin-top: 8px;
    width: 22px;
    height: 22px;
    border-radius: 50%;
    background: rgba(255,43,43,0.25);
    justify-content: center;
    align-items: center;
    color: #ff2b2b;
    cursor: pointer;
    animation: aiPulse 1.2s infinite;
    i { font-size: 14px; }
}

/* 全局下拉菜单深色主题覆盖 - 使用body级别选择器 */
body .el-dropdown-menu {
    background: rgba(3, 12, 49, 0.95) !important;
    border: 1px solid rgba(28, 89, 156, 0.5) !important;
    border-radius: 6px !important;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.6) !important;
}

body .el-dropdown-menu .el-dropdown-menu__item {
    background: transparent !important;
    color: rgba(255, 255, 255, 0.7) !important;
    font-size: 12px !important;
    padding: 8px 16px !important;
    transition: all 0.3s ease !important;
}

body .el-dropdown-menu .el-dropdown-menu__item:hover,
body .el-dropdown-menu .el-dropdown-menu__item:focus {
    background: rgba(28, 89, 156, 0.3) !important;
    color: #fff !important;
}

body .el-dropdown-menu .el-dropdown-menu__item.is-active {
    background: rgba(28, 89, 156, 0.4) !important;
    color: #fff !important;
}

/* 针对popper容器的覆盖 */
body .el-popper .el-dropdown-menu {
    background: rgba(3, 12, 49, 0.95) !important;
    border: 1px solid rgba(28, 89, 156, 0.5) !important;
}
</style>
